gpt4 book ai didi

python - 剥离逗号和句号

转载 作者:太空狗 更新时间:2023-10-30 01:51:42 26 4
gpt4 key购买 nike

我目前正在尝试输入一个文本文件,将每个单词分开并将它们组织成一个列表。

我目前遇到的问题是从文本文件中删除逗号和句号。

我的代码如下:

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com