我目前正在尝试输入一个文本文件,将每个单词分开并将它们组织成一个列表。
我目前遇到的问题是从文本文件中删除逗号和句号。
我的代码如下:
#Process a '*.txt' file.
def Process():
name = input("What is the name of the file you would like to read from? ")
file = open( name , "r" )
text = [word for line in file for word in line.lower().split()]
word = word.replace(",", "")
word = word.replace(".", "")
print(text)
我目前得到的输出是这样的:
['this', 'is', 'the', 'first', 'line', 'of', 'the', 'file.', 'this', 'is', 'the', 'second', 'line.']
如您所见,"file"和“行”这两个词的末尾都有一个句点。
我正在阅读的文本文件是:
This is the first line of the file.
This is the second line.
提前致谢。
最佳答案
这些行没有效果
word = word.replace(",", "")
word = word.replace(".", "")
只需将您的列表组件更改为:
[word.replace(",", "").replace(".", "")
for line in file for word in line.lower().split()]
关于python - 剥离逗号和句号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15536287/