2017-04-10 77 views
-1

我想分割一個文本文件。它來作爲一個大段落。我想把它分成更小的句子,每個句子都是一個列表。從那裏我可以找出哪些列表包含特定的單詞。將文本段落拆分成句子

這是我的代碼,因爲它是目前:

import string 

Done = False 
while not Done: 
    try: 
     File = input("Enter your file: ") 
     Open_File = open(File, "r") 
     Info = Open_File.readline() 
     print(Info) 
     Open_File.close() 
     Done = True 
    except FileNotFoundError: 
     print("Sorry that file doesn't exist!") 


Info_Str = str(Info) 
Info_Str = Info_Str.lower() 
Info_Str = Info_Str.replace("'", "") 
Info_Str = Info_Str.replace("-", "") 
Info_Str = Info_Str.split() 
Info_List = Info_Str 
Info_List = [''.join(c for c in s if c not in string.punctuation) for s in Info_List] 
New_List = [item for item in Info_List if not item.isdigit()] 
for word in New_List[:]: 
    if len(word) < 3: 
     New_List.remove(word) 
print(New_List) 

如果我把一個文本文件,它只返回一個文本文件的第一行字的列表。

如何將每個單獨的句子轉換爲單獨的單詞列表?提前致謝。

+0

您確切的要求是什麼?如果您只想獲取文件中的單詞列表,則可以只讀取所有行並使用空格分隔符進行分隔。 – Geetanjali

+0

我基本上必須找出哪個行號出現一個特定的單詞。每一行都是一個單獨的句子。 – Amaranthus

+0

檢查我發佈的代碼段。這應該有所幫助。 – Geetanjali

回答

1

你寫的代碼有點大。您可以使用較少數量的代碼行來完成此任務。讓我們先來看看我們如何實現它:

  1. 使用with聲明打開文件。 with聲明的好處你不必明確關閉文件。
  2. 該段落可以使用「。」分割爲一行。要麼 」?」。
  3. 每行可以使用單個空格拆分成列表。
  4. 然後,您可以在該列表中搜索您想要的單詞。

代碼:

#open File 
with open("a.txt") as fh: 
    for line in fh: 
     #Split Paragraph on basis of '.' or ? or !. 

     for l in re.split(r"\.|\?|\!",line): 
      #Split line into list using space. 
      tmp_list = l.split(" ") 
      #Search word and if found print that line 
      if "Dinesh" in tmp_list: 
       print l 

注:我的代碼還可以優化。我想,既然你剛剛開始,這對你有好處。

+0

我接受了一個重擊,然後我意識到:並非所有的句子都必然結束(?,!等)。我認爲導致「它只返回文本文件的第一行作爲單詞列表」的原始錯誤。錯誤是這一行:'Info = Open_File.readline()' – JacobIRR

+0

在你的情況下,每行不是用'。'分隔的行。假設我有 'Hello.new line \ n 同一行.' '新行'和'同一行'將出現在不同的列表中。 – Geetanjali

+0

我試着用'Info = Open_File.read()'來代替它,但它只是將整個段落作爲一個大單詞列表返回,而不是在每個新句子處將其分開。 – Amaranthus

0

這將打印句子編號(0索引)。

with open("sample.txt") as f: 
    content = f.read() # Read the whole file 
    lines = content.split('.') # a list of all sentences 
    for num,line in enumerate(lines): # for each sentence 
      if 'word' in line: 
       print(num) 
      else: 
       print("Not present")