【问题标题】:Remove punctuation from textfile error - Python 3从文本文件错误中删除标点符号 - Python 3
【发布时间】:2018-11-17 23:00:26
【问题描述】:

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

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' 没有任何标点符号。我希望程序打印文档中存在的所有文本,这些文本有几段长。任何帮助将不胜感激!

【问题讨论】:

    标签: python-3.x filenames


    【解决方案1】:

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

    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'))
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 2019-08-04
      • 2019-04-26
      • 1970-01-01
      相关资源
      最近更新 更多