简体   繁体   English

带有re和csv的Python“ TypeError:预期的字符串或缓冲区”

[英]Python “TypeError: expected string or buffer” with re and csv

So I am working on a program that grabs a Twitter username from a csv file and plugs it into a function that downloads all the tweets. 因此,我正在开发一个程序,该程序从csv文件中获取Twitter用户名,并将其插入下载所有tweet的函数中。 I pretty much have gotten it to work except I think the output of the row from the csv has brackets and apostrophes, ['POTUS'] instead of POTUS , which Twitter won't accept. 除我认为csv的行输出带有方括号和撇号( ['POTUS']而不是Twitter不会接受的POTUS ,我几乎已经使它工作了。

Here is the code I am using: 这是我正在使用的代码:

with open('names.csv') as namescsv:
    namereader = csv.reader(namescsv)
    for row in namereader:
        row = re.sub(r'[^\w=]', '',row)
        print row

I used re to try to remove the odd characters, but when I execute the code I get this error: 我用re尝试删除了奇数字符,但是当我执行代码时,出现此错误:

File "/home/ian/Desktop/tweepy_scripts/tweetdownloader_allcsv_v2.py", line 66, in <module>
    row = re.sub(r'[^\w=]', '',row)
File "/usr/lib/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer

Some help would be awesome! 一些帮助会很棒! I'm a beginner and my attempts to solve the problem using previous articles hasn't yielded much. 我是一个初学者,使用以前的文章解决该问题的尝试并没有产生太大的效果。

I think the output of the row from the csv has brackets and apostrophes, ['POTUS'] instead of POTUS 我认为csv行的输出具有方括号和撇号, ['POTUS']而不是POTUS

No, it doesn't. 不,不是。 The output of the row from the csv module is a list of str s. 来自csv模块的行的输出是strlist When you display the list (using, for example, print ), it is displayed with the punctuation you describe. 当显示列表时(例如,使用print ),该列表将显示您所描述的标点符号。

Instead of passing row off to the Twitter API, you might need to pass a single cell of the row. 您可能需要传递该行的单个单元格,而不是将row传递给Twitter API。 The first cell is called row[0] , so you might need: 第一个单元格称为row[0] ,因此您可能需要:

result = whatever.the.twitter.api.is.called(row[0]) 

It's because your row variable is a list, not a string - and Python is warning you that it expects a string. 这是因为您的行变量是列表,而不是字符串-Python警告您需要字符串。 try something like this: 尝试这样的事情:

import csv
import re

with open('names.csv') as namescsv:
    namereader = csv.reader(namescsv)
    for row in namereader:
        for cell in row:
            cell = re.sub(r'[^\w=]', '',cell)
            print cell

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM