【问题标题】:How to remove prefixed u from a unicode string?如何从 unicode 字符串中删除前缀 u?
【发布时间】:2019-05-30 11:43:22
【问题描述】:

我正在读取 CSV 文件中的行;我正在应用 LDA 算法来查找最常见的主题,在 doc_processed 中进行数据处理后,我在每个单词中都得到了“u”,但为什么呢?请建议我从 doc+processed 中删除 'u',我在 Python 2.7 中的代码是

data = [line.strip() for line in open("/home/dnandini/test/h.csv", 'r')]

stop = set(stopwords.words('english'))# stop words
exclude = set(string.punctuation) #to reomve the punctuation
lemma = WordNetLemmatizer() # to map with parts of speech

def clean(doc):

    stop_free = " ".join([i for i in doc.lower().split() if i not in stop])
    punc_free = ''.join(ch for ch in stop_free if ch not in exclude)
    normalized = " ".join(lemma.lemmatize(word) for word in punc_free.split())
    shortword = re.compile(r'\W*\b\w{1,2}\b')
    output=shortword.sub('', normalized)   
    return output  
doc_processed = [clean(doc) for doc in data] 

输出为 doc_processed -

 [u'amount', u'ze69heneicosadien11one', u'trap', u'containing', u'little', u'microg', u'zz69ket', u'attracted', u'male', u'low', u'population', u'level', u'indicating', u'potent', u'sex', u'attractant', u'trap', u'baited', u'z6ket', u'attracted', u'male', u'windtunnel', u'bioassay', u'least', u'100fold', u'attractive', u'male', u'zz69ket', u'improvement', u'trap', u'catch', u'occurred', u'addition', u'z6ket', u'various', u'binary', u'mixture', u'zz69ket', u'including', u'female', u'ratio', u'ternary', u'mixture', u'zz69ket']

【问题讨论】:

    标签: python-2.7 list set lda


    【解决方案1】:

    u'some string' 格式意味着它是一个 unicode 字符串。有关 unicode 字符串本身的更多详细信息,请参阅 this question,但解决此问题的最简单方法可能是在从 clean 返回结果之前先将结果 str.encode

    def clean(doc):
        # all as before until
        output = shortword.sub('', normalized).encode()
        return output
    

    请注意,尝试对不直接转换为默认编码(似乎是 ASCII。请参阅系统上的 sys.getdefaultencoding() 进行检查)的 unicode 代码点进行编码将在此处引发错误。您可以通过定义 errors kwarg 进行编码以各种方式处理错误。

    s.encode(errors="ignore")  # omit the code point that fails to encode
    s.encode(errors="replace")  # replace the failing code point with '?'
    s.encode(errors="xmlcharrefreplace") # replace the failing code point with ' '
    # Note that the " " above is U+FFFD, the Unicode Replacement Character.
    

    【讨论】:

      猜你喜欢
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 2010-10-20
      • 2017-03-22
      相关资源
      最近更新 更多