我正在尝试拆分文本文件。它是一个很大的段落。我想把它分成更小的句子,让每个句子成为一个列表。从那里我可以找出哪些列表包含特定单词。
这是我目前的代码:
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)
如果我放入文本文件,它只返回文本文件的第一行作为单词列表。
如何让它将每个单独的句子转换为单独的单词列表?谢谢,提前。
你写的代码有点大。您可以在更少的代码行数中完成此任务。让我们首先了解我们如何实现它:
- 使用
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
注意:我的代码也可以优化。我想,既然你刚刚开始,这对你有好处。
这将
打印句子编号(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")