【问题标题】:Trying to remove all non-english characters from list of strings试图从字符串列表中删除所有非英语字符
【发布时间】:2018-02-07 16:43:52
【问题描述】:

我有一个字典列表

Amazon 120 
b 19 
maji_opai 1 
am\xcd\x9ca\xcd\x89zon\xe2\x80\xa6 1 
\xcb\x99\xea\x92\xb3\xe2\x80\x8b\xcb\x99 1 
b'RT 46 
WorkingGIrl 1 
For 1 
people 1 
love 1 
REAL 1 
paperback 1 
THE 3 
PARIS 1 
EFFECT 1 
10 1 
right 1 

并且在删除字符和非英语单词时遇到了麻烦。Twitter 抓取的目标是创建一个简单的词频计数。

有没有最好的方法来创建一个循环并删除所有非英语单词/字符?

我用来创建字数字典的这段代码

wordcount={}

for word in lemma_list:
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1

for key in wordcount.keys():
    print ("%s %s " %(key , wordcount[key]))

print(type(wordcount.keys()))
   <class 'dict_keys'>

【问题讨论】:

  • list 在哪里,dictionaries 在哪里?
  • 对不起。刚习惯在这里发问题。我编辑了用于获取字典列表的代码
  • 你需要找一本字典来比较。否则,您将仅限于扔掉带有非 ASCII 字符的单词,这不会告诉您它是否是一个真实的单词,也不会告诉您它是否是英文的。一旦你有了它,你可能会研究某种拼写检查算法来解决拼写错误,但这很快就会变得相当复杂。

标签: python python-3.x for-loop nltk


【解决方案1】:

如果“英文”字符是指"ascii",则使用string.printable,这是一组所有ASCII 可打印字符

import string
ascii_chars = set(string.printable)  # speeds things up
def remove_non_ascii_prinatble_from_list(list_of_words):
    return [word for word in list_of_words 
            if all(char in ascii_chars for char in word)]

或者在字典上

def remove_non_ascii_prinatble_keys_from_dict(dict_of_words):
    return {key: value for key, value in dict_of_words.items() 
            if all(char in ascii_chars for char in key)}

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 1970-01-01
    • 2010-12-04
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多