从文本文件错误中删除标点符号-Python 3

时间:2018-11-17 23:00:27

标签: python-3.x filenames

我正在尝试制作一个程序来删除文本文件中的所有标点符号,但是我一直遇到一个错误,即它仅打印文件标题而不是文件内容。

def removePunctuation(word):
    punctuation_list=['.', ',', '?', '!', ';', ':', '\\', '/', "'", '"']

    for character in word:
        for punctuation in punctuation_list:
            if character == punctuation:
                word = word.replace(punctuation, "")

    return word
print(removePunctuation('phrases.txt'))

每当我运行代码时,它只会打印文件的名称; 'phrasestxt',没有任何标点符号。我希望程序打印文档中存在的所有文本,该文本有几段长。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

在这种情况下,您必须打开文件并阅读:

def removePunctuation(file_path):
    with open(file_path, 'r') as fd:
        word = fd.read()
    punctuation_list=['.', ',', '?', '!', ';', ':', '\\', '/', "'", '"']

    for character in word:
        for punctuation in punctuation_list:
            if character == punctuation:
                word = word.replace(punctuation, "")

    return word
print(removePunctuation('phrases.txt'))

如果需要,可以将double for循环替换为

word = "".join([i for i in word if i not in punctuation_list])