我正在尝试用Python3.7.2编写Python代码,以便在同一目录下的多个UTF8文本文件中删除所有中文字符中的空格。
我目前的代码只适用于一个文件:
import re
with open("transcript 0623.txt") as text:
new_text = re.sub("(?<![ -~]) (?![ -~])", "", text)
with open("transcript 0623_out.txt", "w") as result:
result.write(new_text)我得到以下错误:
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Wave.3\test.py", line 4, in <module>
new_text = re.sub("(?<![ -~]) (?![ -~])", "", text)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\Lib\re.py", line 192, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object你能告诉我哪里出了问题并帮我提出改进代码的建议吗?谢谢。
发布于 2019-11-17 20:16:10
open()返回文件对象(来源:https://docs.python.org/3/library/functions.html#open)
如果要对文件内容执行正则表达式操作,则必须在文件对象上使用.read()函数来获取文本内容。
例如,
with open("transcript 0623.txt") as f:
text = f.read()
new_text = re.sub("(?<![ -~]) (?![ -~])", "", text)
with open("transcript 0623_out.txt", "w") as result:
result.write(new_text)https://stackoverflow.com/questions/58900245
复制相似问题