首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用string.punctuation删除字符串的标点符号时出错

使用string.punctuation删除字符串的标点符号时出错
EN

Stack Overflow用户
提问于 2020-01-28 03:50:56
回答 1查看 565关注 0票数 0

快速问题:

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

我已经在几个原始文本块上分别测试了每个组件,因为我还在习惯这个过程,它看起来很好。

代码语言:javascript
复制
    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')]

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

未处理:

代码语言:javascript
复制
    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

已处理:

代码语言:javascript
复制
    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

对这里出了什么问题有什么想法吗?我已经看过文档了,我还没有看到任何人以完全相同的方式来解决这个问题,所以我想要一些关于如何解决这个问题的见解。非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-28 04:32:08

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

我会做类似这样的事情

代码语言:javascript
复制
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值的格式可能会略有不同

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59937943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档