遇到TypeError:预期的字符串或类似字节的对象

时间:2019-09-30 18:31:13

标签: python python-3.x

我尝试将某人使用Python 2编写的某些代码转换为Python 3,但是当我尝试运行它时遇到TypeError。

代码:

text = open("C:\\Users\\Tableu\\Documents\\ICS Twitter stream\\Twitter stream\\community_tweets.txt", "r").readlines()
tweetids = re.findall("\"id\":(\d{18}),",text)
for tid in tweetids:
    count=count+1
    ff.write(str(count)+","+tid+"\n")
text0 = re.split("\n",text)

错误:

Traceback (most recent call last):
  File "c:/Users/Tableu/Documents/ICS Twitter stream/Twitter stream/Cleaning.py", line 11, in <module>
    tweetids = re.findall("\"id\":(\d{18}),",text)
  File "C:\Users\Tableu\AppData\Local\Programs\Python\Python36\lib\re.py", line 222, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object

这是它试图阅读的文本的相关部分:

{"created_at":"Mon Sep 30 09:50:49 +0000 2019","id":1178608124464451585,"id_str":"1178608124464451585"

谢谢!

1 个答案:

答案 0 :(得分:1)

readlines()函数返回字符串列表。我想你想要:

text = "\n".join(open("C:\\Users\\Tableu\\Documents\\ICS Twitter stream\\Twitter stream\\community_tweets.txt", "r").readlines())
tweetids = re.findall("\"id\":(\d{18}),",text)
for tid in tweetids:
    count=count+1
    ff.write(str(count)+","+tid+"\n")
text0 = re.split("\n",text)