python - Replace() 方法在函数中不起作用
问题描述
我正在制作一个接受纯文本文件的函数,然后返回该文件中的单词列表。显然,我想去掉任何换行符 '\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()' 方法不起作用?
解决方案
这可能是 python 或其他一些编程语言将换行读取为 '\n' 转义字符的情况。因此,当 python 读取您的文件时,'\n' 表示新行,'\\n' 表示您在文本文件中写入的实际 '\n' 字符。
所以你需要更换像
a = message.replace('\\n', '')
推荐阅读
- spring-batch - Spring批处理实例id重复键错误,尝试从#1开始
- mongodb - MongoDB连接安全
- javascript - 如果 CDN 失败,如何使用 javascript 回退到本地服务器以获得 fontawesome?
- python - 如何将包含列表字符串的字节转换为 Python 对象?
- javascript - 如何将类添加和删除到 div 元素纯 javascript
- java - 如何从 CallableStatement 样板代码中删除重复项?
- node.js - 获得与 Node.js 一起使用的安全 WebSocket 的最低要求是什么?
- sql - 将所有位置分组到一个位置
- javascript - 与 javascript innerText 属性混淆
- java - 绘制圆形对象后将其传递给 Arraylist