首页 > 文章列表 > Python findall 函数比较 docx 文档文本时出现 "expected string or bytes-like object" 错误如何解决?

Python findall 函数比较 docx 文档文本时出现 "expected string or bytes-like object" 错误如何解决?

448 2024-11-15

Python findall 函数比较 docx 文档文本时出现

python 中 findall 比较函数出错的解决方法

在 python 中使用 findall 函数比较 docx 文档中的文本是否在文本文件中存在时,可能会遇到 "expected string or bytes-like object" 错误。这是因为 findall 函数需要一个字符串或字节序列作为参数,而它收到了一个 paragraph 对象列表。

要解决此问题,需要将 paragraph 对象转换为字符串。可以按照以下步骤进行修改:

result_comp = compiletext.findall(' '.join([p.text for p in doccontent.paragraphs]))

' '.join([p.text for p in doccontent.paragraphs]) 将 paragraph 对象列表转换为单一字符串,从而使其与 findall 函数的参数类型兼容。

来源:1730773420