【问题标题】:Convert a list of 'utf-8' encoded strings into regular strings将“utf-8”编码字符串列表转换为常规字符串
【发布时间】:2017-11-28 14:57:08
【问题描述】:

我正在使用 tweepy 库来获取推文文本列表,我需要将 200 条推文中的单词与停用词列表进行比较,并删除推文文本列表中的停用词,这样我才能说出这些词是什么在搜索的推文中出现最多的。

问题是当我检索 tweet.texts 时,我必须对其进行编码才能得到它,因此我得到了一个 b'word' 列表,它无法与我的常规字符串停用词列表进行比较。

def get_tweetwords():
    print("Ingrese el hashtag a buscar, no olvide escribir el numeral (#)(Ctrl+3)")
    hashtag=str(input())
    while (hashtag[0])!="#":
        print("No olvide escribir el numeral. Vuelva a escribir el hashtag:")
        hashtag=str(input())
    busqueda=tweepy.Cursor(api.search,q=hashtag).items(10)
    twlist=[]
    listadepalabras=[]
    for tweets in busqueda:
        twlist.append(tweets.text.encode('utf-8'))
    for i in twlist:
        x=i.split()
    for j in x:
        listadepalabras.append(j)
    return(listadepalabras)

我需要将listadepalabras 列表解码为字符串列表,以便将其与stopwords 列表进行比较并删除其停用词。

def get_stopwords():   
    listastopwords=[item for item in open("stopwords.txt").readlines()]
    for item in listastopwords:
        if "\n" in listastopwords:
           listastopwords[listastopwords.index(item)]=item.replace("\n","")
    return(listastopwords)

def sacar_stopwords():
    listadepalabras=get_tweetwords()
    listastopwords=get_stopwords()
    for i in listadepalabras:
        for j in listastopwords:
            if i==j:
                listadepalabras.remove(j)
    return(listadepalabras)

这不起作用,因为我的文本列表包含 b'word' 格式的单词,而我的停用词列表只是 'word'

def repeticiones_palabra():
    listadepalabras=sacar_stopwords()
    diccionario=collections.Counter(listadepalabras)
    diccionario=dict(diccionario.most_common(10))
    print ("-LAS 10 PALABRAS MAS UTILIZADAS SON-")
    print(diccionario)

这应该让我获得列表中最常用的 10 个单词,并且它运行良好,但我得到的主要是停用词和我寻找的主题标签,因此我可以知道我的停用词没有从列表中删除。

repeticiones_palabra()

我希望我说清楚了,我是 python 和堆栈溢出的初学者。提前致谢。

【问题讨论】:

  • b 是字节字符串,而不是 UTF-8 字符串。使用:b"abcde".decode("utf-8")

标签: python string list twitter utf-8


【解决方案1】:

b'some string' 是 BYTESTRING

要将其转换为常规字符串,必须使用字符串对象的 .decode() 内置函数:

lst = [b'abc', b'def']
# >>> [b'abc', b'def']
lst2 = [s.decode("utf-8") for s in lst]
# >>> ['abc', 'def']

编辑: 我看到你之前在线编码字符串

for tweets in busqueda:
    twlist.append(tweets.text.encode('utf-8'))

为什么要编码然后又要解码?

只需将其更改为:

for tweets in busqueda:
    twlist.append(tweets.text)

【讨论】:

  • 因为如果我不解码程序就会中断,我需要搜索 200 条推文,而且如果没有编码,我似乎无法获得它们。无论如何,我设法做某事,将列表中的项目一一解码!看起来它现在正在工作。我会在一分钟内添加新代码。
  • 这就是我写的:lst2 = [s.decode("utf-8") for s in lst]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 2011-05-20
  • 1970-01-01
  • 2011-08-16
  • 2016-10-01
  • 2016-05-16
相关资源
最近更新 更多