python - 为什么python代码没有打开文件夹中的所有文本文件?
问题描述
我编写了一些代码,可以打开文件夹中的所有文本文件,删除某些单词,然后将内容写入新的文本文件。我正在使用的文件是在 Windows 机器上创建的,保存在 utf-8 中,然后下载到 mac(有问题)。该代码适用于 250 个文件中的 66 个,然后中断。我收到以下错误:
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-51-7c4734f2a95f> in <module>
1 for file in os.listdir(path):
2 with open(file, 'r', encoding='utf-8') as f:
----> 3 flines = f.readlines()
4 new_content = []
5 for line in flines:
~/anaconda/lib/python3.7/codecs.py in decode(self, input, final)
320 # decode input (taking the buffer into account)
321 data = self.buffer + input
--> 322 (result, consumed) = self._buffer_decode(data, self.errors, final)
323 # keep undecoded input until the next call
324 self.buffer = data[consumed:]
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 287: invalid start byte
我已经使用 file -I {filename} 检查了一些没有在终端中转换的文件的文件编码,它确实说 charset=utf-8。但是我认为问题一定是编码。
我试过做'encoding='ascii'',并使用'rb'而不是'r',但没有成功。我认为这可以帮助我,但我不知道如何将它合并到我的代码中https://www.programiz.com/python-programming/methods/string/encode。
任何帮助将非常感激。
for file in os.listdir(path):
with open(file, 'r', encoding='utf-8') as f:
flines = f.readlines()
new_content = []
for line in flines:
content = line.split()
new_content_line = []
new_content_line2 = []
fillers = ['um', 'uum', 'umm', 'er', 'eer', 'uh', 'ah', 'ahh', 'hm', 'hmm', 'mm', 'Um', 'Uum', 'Umm', 'Er', 'Eer', 'Uh', 'Ah', 'Ahh', 'Hm', 'Hmm', 'Mm']
for word in content:
if not word.startswith('[=')and not word.startswith('#') and not word.startswith('..') and not word.endswith(']') and not word.endswith('='):
new_content_line.append(word)
for word in new_content_line:
if word not in fillers:
new_content_line2.append(word)
new_content_line2 = [x.lower() for x in new_content_line2]
for v, w in zip(new_content_line2[:-1],new_content_line2[1:]):
if v == w:
new_content_line2.remove(v)
new_content.append(' '.join(new_content_line2))
f2 = open((file.rsplit( ".", 1 )[ 0 ] ) + "_processed.txt", "w", encoding = 'utf-8')
f2.write('\n'.join(new_content))
f.close
f2.close
解决方案
推荐阅读
- php - 如何在 VB.net 中转换 JSON 以便在 PHP 中使用
- swift - 仅当 loadRequest 在 viewDidLoad 之外时 UIWebView 的 Nil 错误
- unit-testing - Uber Cadence:如何断言对 workflow.Sleep() 的调用?
- cadence-workflow - Uber Cadence 本地活动与副作用
- laravel - 一些 postgress 连接超时,而另一些则没有
- kubernetes - 我可以使用模板来部署 Kubernetes 吗?
- python-3.x - 如何找到需要优化的代码部分?
- gremlin - 无法添加新顶点
- mysql - 制作最准确的数据结构——mySQL
- python - 根据某些值比较两个字典列表