python - 读取文本文件时删除标点符号[python]

标签 python

我正在编写一个Python程序,它将文本文件的内容读入数组/列表,但我在从文本文件中删除标点符号时遇到问题。这是我尝试过的:

def read_file(self,filename):
    name_file = filename
    filename = open(name_file, 'r')
    file = filename
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    no_punct = ""
    lst = []
    for word in file:
        word = word.strip('\n')
        for char in punctuations:
            word = word.strip(char)
        lst.append(word)


    filename.close()

在我删除字符的部分,我注意到word文件中内容的顺序也发生了变化,并且一些标点符号没有完全删除。

如果我使用“替换”方法,它效果很好,但我正在寻找一种不使用替换内置函数的方法。

最佳答案

我注意到的一些事情只会导致部分标点符号被删除。 for word in file: 行实际上应该是 for line in file:。 Python 按行而不是按单词迭代文件。 strip 函数仅删除开头和结尾的项目。您可以使用 replace 函数删除中间的字符。目前程序的编写方式,只会删除文档中每行开头和结尾的标点符号。

我删除所有标点符号的方式就像这样。

from pathlib import Path
import string

filepath = Path(filename)
text = filepath.read_text()
text = text.replace(string.punctuation, "")
filepath.write_text(text )

但是你说替换功能与电子书功能混淆了。你能再详细解释一下吗?我不明白替换每个单词中的标点符号与一次性替换整个文件中的标点符号有何不同?

关于python - 读取文本文件时删除标点符号[python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46627435/

相关文章:

python - 将图像转换为灰度

Python float 到字符串 : how to get '0.03' but '-.03'

python - 使用 unittest discover 传递参数(对于 argparse)

Python:如何使用 PyQt 调整光栅图像的大小

python - 类型为 ="previous"的 scipy.interpolate.interp1d 未按预期进行推断

Python 的 time.clock() 与 time.time() 的准确性?

python - 使用 Marshmallow 反序列化强制执行严格的字段。日期格式

python - 在 INSERT 中使用 WHERE … ON CONFLICT …

python - 如何在 Python 中使用 OpenCV 裁剪图像的黑色背景?

python - 使用seaborn.distplot绘制密度图时如何防止seaborn平滑直方图?