【发布时间】:2023-03-28 02:32:02
【问题描述】:
我想阅读几个 .text 文档,但出现了一些错误
lyrics = "".join(f.readlines())
错误是:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 1148: character maps to <undefined>
我该如何解决它。如果有人修复它会很有帮助。
我的代码功能是:
def read_lyrics():
reg1 = re.compile("\.txt$")
reg2 = re.compile("([0-9]+)\.txt")
reg3 = re.compile(".*_([0-9])\.txt")
reg4 = re.compile("\[.+\]")
reg5 = re.compile("info\.txt")
lyrics_dictionary = {}
#iter all directory and load all song(txt file)
for i in os.listdir():
if os.path.isdir(i):
for path,sub,items in os.walk(i):
if any([reg1.findall(item) for item in items]):
for item in items:
if reg5.findall(item):
continue
if reg3.findall(item):
num = ["0"+reg3.findall(item)[0]]
name = "_".join(path.split("/") + num)
else:
name = "_".join(path.split("/") + reg2.findall(item))
print("The path is: ", path)
print("The item is: ", item)
with open(os.path.join(path,item),"r") as f:
print("The file path is: ", f)
lyrics = "".join(f.readlines())
lyrics = reg4.subn("",lyrics)[0]
lyrics_dictionary[name] = lyrics
return lyrics_dictionary
【问题讨论】:
-
那么当您尝试将
'charmap'+codec+can't+decode+byte+0x8d+in+position+1148放入搜索引擎,查看the results,并尝试结果中的建议时,发生了什么? -
您的
open电话是open(os.path.join(path,item),"r") as f。在 Python 3 中,它会打开一个默认编码为 UTF-8 的文件。但是您收到一条关于charmap 编码的错误消息,这表明您可能正在Python 2 中运行此代码。如果您是,您的print()调用会将parens 放入输出中,如('The path is', '...')。跨度>