TypeError: 序列项 1: 需要一个类似字节的对象,找到了 str

新手上路,请多包涵

我正在尝试使用 Python 3 中的正则表达式从文本文件中的维基标题转储中提取英文标题。维基转储还包含其他语言的标题和一些符号。下面是我的代码:

 with open('/Users/some/directory/title.txt', 'rb')as f:
    text=f.read()
    letters_only = re.sub(b"[^a-zA-Z]", " ", text)
    words = letters_only.lower().split()
print(words)

但我收到一个错误:

 TypeError: sequence item 1: expected a bytes-like object, str found

在该行: letters_only = re.sub(b"[^a-zA-Z]", " ", text)

但是,我正在使用 b'' 将输出作为字节类型,下面是文本文件的示例:

 Destroy-Oh-Boy!!
!!Que_Corra_La_Voz!!
!!_(chess)
!!_(disambiguation)
!'O!Kung
!'O!Kung_language
!'O-!khung_language
!337$P34K
!=
!?
!?!
!?Revolution!?
!?_(chess)
!A_Luchar!
!Action_Pact!
!Action_pact!
!Adios_Amigos!
!Alabadle!
!Alarma!
!Alarma!_(album)
!Alarma!_(disambiguation)
!Alarma!_(magazine)
!Alarma!_Records
!Alarma!_magazine
!Alfaro_Vive,_Carajo!
!All-Time_Quarterback!
!All-Time_Quarterback!_(EP)
!All-Time_Quarterback!_(album)
!Alla_tu!
!Amigos!
!Amigos!_(Arrested_Development_episode)
!Arriba!_La_Pachanga
!Ask_a_Mexican!
!Atame!
!Ay,_Carmela!_(film)
!Ay,_caramba!
!BANG!
!Bang!
!Bang!_TV
!Basta_Ya!
!Bastardos!
!Bastardos!_(album)
!Bastardos_en_Vivo!
!Bienvenido,_Mr._Marshall!
!Ciauetistico!
!Ciautistico!
!DOCTYPE
!Dame!_!Dame!_!Dame!
!Decapitacion!
!Dos!
!Explora!_Science_Center_and_Children's_Museum
!F
!Forward,_Russia!
!Forward_Russia!
!Ga!ne_language
!Ga!nge_language
!Gã!ne
!Gã!ne_language
!Gã!nge_language
!HERO
!Happy_Birthday_Guadaloupe!
!Happy_Birthday_Guadalupe!
!Hello_Friends

我在网上搜索过,但没有成功。任何帮助将不胜感激。

原文由 Sherlock 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 757
2 个回答

您必须在二进制和文本模式之间进行选择。

Either you open your file as rb and then you can use re.sub(b"[^a-zA-Z]", b" ", text) ( text is a bytes object)

Or you open your file as r and then you can use re.sub("[^a-zA-Z]", " ", text) ( text is a str object)

第二种解决方案更“经典”。

原文由 Jean-François Fabre 发布,翻译遵循 CC BY-SA 3.0 许可协议

问题在于您提供的 repl 参数,它不是 bytes 对象:

 letters_only = re.sub(b"[^a-zA-Z]", " ", b'Hello2World')
# TypeError: sequence item 1: expected a bytes-like object, str found

相反,提供 repl 作为字节实例 b" "

 letters_only = re.sub(b"[^a-zA-Z]", b" ", b'Hello2World')
print(letters_only)
b'Hello World'


注意:不要在文字前面加上 b 并且不要用 rb 打开文件如果你不是在寻找 byte

原文由 Dimitris Fasarakis Hilliard 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题