从文本文件错误中删除标点符号 - Python 3
Remove punctuation from textfile error - Python 3
我正在尝试制作一个程序,从文本文件中删除所有标点符号,但是我一直 运行ning 出错,它只打印文件的标题而不是文件中的内容。
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' 没有任何标点符号。我希望程序打印文档中存在的所有文本,文档有几段那么长。如有任何帮助,我们将不胜感激!
在这种情况下,您必须打开文件并阅读它:
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'))
如果需要,您可以将双循环替换为
word = "".join([i for i in word if i not in punctuation_list])
我正在尝试制作一个程序,从文本文件中删除所有标点符号,但是我一直 运行ning 出错,它只打印文件的标题而不是文件中的内容。
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' 没有任何标点符号。我希望程序打印文档中存在的所有文本,文档有几段那么长。如有任何帮助,我们将不胜感激!
在这种情况下,您必须打开文件并阅读它:
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'))
如果需要,您可以将双循环替换为
word = "".join([i for i in word if i not in punctuation_list])