python - 剥离逗号和句号

标签 python file-io stripping

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

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

我的代码如下:

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

相关文章:

python - 在 python 中为大文件创建校验和的最快方法

python - 如何使 Tkinter 窗口不可调整大小?

c - printf 和 fprintf 之间的不同行为

即使 CSS.AllowTricky 设置为 True,HTML_purifier 也会剥离显示 :none css from images,?

javascript - 使用 javascript 删除除 <br> 或 <br/> 标签之外的 html 标签

python - 为什么这两个字符串在Python中不相等?

python PIL YCbCr 支持

mysql - 选择时剥离

c - 为什么这段代码给出了错误的文件描述符

perl - ./script 第 17 行没有这样的文件或目录