我尝试将某人使用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"
谢谢!
答案 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)