【问题标题】:Error when using string.punctuation to remove punctuation for a string使用 string.punctuation 删除字符串的标点符号时出错
【发布时间】:2020-01-27 19:50:56
【问题描述】:

快速提问:

我正在使用stringnltk.stopwords 将一段文本中的所有标点符号和停用词作为数据预处理的一部分,然后再将其输入一些自然语言处理算法。

我已经在几个原始文本块上分别测试了每个组件,因为我仍然习惯这个过程,而且看起来还不错。

    def text_process(text):
        """
        Takes in string of text, and does following operations: 
        1. Removes punctuation. 
        2. Removes stopwords. 
        3. Returns a list of cleaned "tokenized" text.
        """
        nopunc = [char for char in text.lower() if char not in string.punctuation]

        nopunc = ''.join(nopunc)

        return [word for word in nopunc.split() if word not in 
               stopwords.words('english')]

但是,当我将此函数应用于我的数据框的文本列时——它是来自一堆 Pitchfork 评论的文本——我可以看到标点符号实际上并没有被删除,尽管停用词被删除了。

未处理:

    pitchfork['content'].head(5)

0    “Trip-hop” eventually became a ’90s punchline,...
1    Eight years, five albums, and two EPs in, the ...
2    Minneapolis’ Uranium Club seem to revel in bei...
3    Minneapolis’ Uranium Club seem to revel in bei...
4    Kleenex began with a crash. It transpired one ...
Name: content, dtype: object

已处理:

    pitchfork['content'].head(5).apply(text_process)


0    [“triphop”, eventually, became, ’90s, punchlin...
1    [eight, years, five, albums, two, eps, new, yo...
2    [minneapolis’, uranium, club, seem, revel, agg...
3    [minneapolis’, uranium, club, seem, revel, agg...
4    [kleenex, began, crash, it, transpired, one, n...
Name: content, dtype: object

对这里出了什么问题有什么想法吗?我浏览了文档,但我还没有看到任何人以完全相同的方式在这个问题上苦苦挣扎,所以我很想了解如何解决这个问题。非常感谢!

【问题讨论】:

  • 请不要发布代码或数据的图像。将其复制并粘贴为文本,然后将其格式化为代码(选择它并输入ctrl-kDiscourage screenshots of code and/or errors
  • 知道了!我现在就改变它。感谢您的帮助!
  • 没有看到你的实际数据,很难说。但要检查的一件事是,没有被删除的标点符号实际上在 ascii string.punctuation 列表中,而不是其他字符。例如,'?' in '!"\'#$%&()*+,-./:;<=>?@[\]^_{|}~'` 是 True,但是你的引号呢?根据您的更新:" != ”
  • string.punctuation 只包含 ASCII 标点符号。您看到的字符是非 ASCII 大引号。
  • 问题是所有 Unicode 标点符号的列表是巨大的,他们没有尝试枚举所有的。

标签: python nltk punctuation


【解决方案1】:

这里的问题是utf-8对左右引号(单引号和双引号)有不同的编码,而不仅仅是string.punctuation中包含的常规引号。

我会做类似的事情

punctuation = [ c for c in string.punctuation ] + [u'\u201c',u'\u201d',u'\u2018',u'\u2019']

nopunc = [ char for char in text.decode('utf-8').lower() if char not in punctuation ]

这会将非 ascii 引号的 utf-8 值添加到名为 punctuation 的列表中,然后将文本解码为 utf-8,并替换这些值。

注意:这是python2,如果你使用的是python3,utf值的格式可能会略有不同

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 2023-01-03
    相关资源
    最近更新 更多