在Python中解析CSV列中的推文
我正在尝试从推文中提取标签(hashtags)。所有的推文都在一个CSV文件的同一列里。虽然网上有一些关于如何解析字符串并把提取的标签放进列表的资源,但我还没找到关于如何解析已经存储在列表或字典中的推文的解决方案。以下是我的代码:
with open('hash.csv', 'rb') as f:
reader = csv.reader(f, delimiter=',')
for line in reader:
tweet = line[1:2] #This is the column that contains the tweets
for x in tweet:
match = re.findall(r"#(\w+)", x)
if match: print x
我遇到了一个错误,提示'类型错误:期望字符串或缓冲区',这是因为在这个情况下,'tweet'并不是一个字符串,而是一个列表。
到目前为止,我的研究进展如下:
http://www.tutorialspoint.com/python/python_reg_expressions.htm
所以我正在遍历匹配的列表,但我仍然得到了整个推文,而不是带标签的部分。我能够去掉标签,但我想要的是去掉除了标签以外的所有内容。
with open('hash.csv', 'rb') as f:
reader = csv.reader(f, delimiter=',')
for line in reader:
tweet = line[1:2]
print tweet
for x in tweet:
match = re.split(r"#(\w+)", x)
hashtags = [i for i in tweet if match]
1 个回答
0
其实,你的问题可能只是语法上的错误。你在调用 tweet = line[1:2]
。在Python中,这个意思是“从第1个到第2个取一段”,这在逻辑上是你想要的。不过,它返回的结果是一个列表,所以你得到的是 [tweet] 而不是 tweet!
试着把那一行改成 tweet = line[1]
,看看这样能不能解决你的问题。
另外,这可能只是你打错了,但我觉得你应该检查一下缩进,应该像这样:
for line in reader:
tweet = line[1:2] #This is the column that contains the tweets
for x in tweet:
match = re.findall(r"#(\w+)", x)
if match: print x
除非我误解了你的逻辑。