我正在创建一个函数,它接受纯文本文件,然后返回该文件中的单词列表。显然,我想删除任何换行符 '\n',但是,当使用 '.replace()' 时什么也没有发生。
功能:
textfile = 'name.txt'
def read_words(filename):
f = open(filename,'r')
message = f.read()
a = message.replace('\n', '')
wordlist = a.split(' ')
print(wordlist)
read_words(textfile)
示例文本:
This\n\nis\n\n\na\n\n\nmy\n\nwfile with spaces and blanks
我的输出:
['This\\n\\nis\\n\\n\\na\\n\\n\\nmy\\n\\nwfile', 'with', 'spaces', 'and', 'blanks']
为什么“.replace()”方法不起作用?
最佳答案
当前文本替换的问题是 \
被视为转义字符 - 文字字符 \n
被解释为换行符。解决这个问题的方法是通过 \\
转义 \
字符本身。更新后的替换语句将显示为:
a = message.replace('\\n', '')
而不是:
a = message.replace('\n', '')
关于python - Replace() 方法在函数内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55073081/