我正在尝试拆分文本文件。它是一个大段落。我想把它分成更小的句子,每个句子都是一个列表。从那里我可以找出哪些列表包含特定的单词。
这是我目前的代码:
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 :(得分:1)
你写的代码有点大。您可以用较少的代码行来完成此任务。让我们首先了解我们如何实现它:
with
语句打开文件。 with
语句的好处是您不必明确关闭文件。<强>代码:强>
#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
注意:我的代码也可以进行优化。我想,既然你刚刚开始,这对你有好处。
答案 1 :(得分:1)
这将打印句号(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")