【问题标题】:Errors concerning return _compile(pattern, flags).findall(string) TypeError: expected string or bytes-like object有关 return _compile(pattern, flags).findall(string) 的错误 TypeError: expected string or bytes-like object
【发布时间】:2017-11-13 20:28:25
【问题描述】:

我是 Python 的初学者,当我尝试在 CMD 上执行这个命令时,我遇到了这个错误。请指教:

代码:

import re
handle=open('regex_sum_41718.txt')
for line in handle:
    word=line.split()
    print(type(word))
    y=re.findall('[0-9]+',word)
print(y)

错误:

Traceback (most recent call last):
    File "Assi_1.py", line 5, in <module>
        y=re.findall('[0-9]+', word)
    File "D:\Python\lib\re.py", line 222, in findall
        return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object

非常感谢。

【问题讨论】:

    标签: python regex findall


    【解决方案1】:

    你需要在line.split()周围再循环一个:

    for line in handle:
        for word in line.split():
            print(type(word))
            y=re.findall('[0-9]+',word)
    

    否则word是一个列表,只能搜索字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      相关资源
      最近更新 更多