【问题标题】:How to delete certain words from a variable or a list python如何从变量或列表python中删除某些单词
【发布时间】:2015-07-12 09:55:06
【问题描述】:
common_words = set(['je', 'tek', 'u', 'još', 'a', 'i', 'bi',
            's', 'sa', 'za', 'o', 'kojeg', 'koju', 'kojom', 'kojoj',
            'kojega', 'kojemu', 'će', 'što', 'li', 'da', 'od', 'do',
            'su', 'ali', 'nego', 'već', 'no', 'pri', 'se', 'li',
            'ili', 'ako', 'iako', 'bismo', 'koji', 'što', 'da', 'nije',
            'te', 'ovo', 'samo', 'ga', 'kako', 'će', 'dobro',
            'to', 'sam', 'sve', 'smo', 'kao'])
all = []


for (item_content, item_title, item_url, fetch_date) in cursor:
             #text = "{}".format(item_content)
             text= item_content
             text= re.sub('[,.?";:\-!@#$%^&*()]', '', text)
             text = text.lower()
             #text = [w for w in text if not w in common_words]
             all.append(text)

我想从变量“test”中删除某些单词/停用词,或者稍后从列表“all”中删除迭代中的所有“text”变量。

我这样尝试过,但这不仅会删除单词,还会删除那些字母,如果它们存在于其他单词中,并且每个单词的输出都像'd','f',我希望格式保持不变同样,我只需要从变量(或列表)中删除 common_words 列表中的那些单词。我将如何实现这一目标?

【问题讨论】:

    标签: python text replace stop-words


    【解决方案1】:

    作为一种从测试中删除标点符号的pythonic方法,您可以使用str.translate方法:

    >>> "this is224$# a ths".translate(None,punctuation)
    'this is224 a ths'
    

    要替换单词使用re.sub,首先创建正则表达式,将点子(|)附加到单词:

    reg='|'.join(common_words)
    new_text=re.sub(reg,'',text)
    

    示例:

    >>> s="this is224$# a ths"
    >>> import re
    >>> w=['this','a']
    >>> boundary_words=['\b{}\b'.format(i) for i in w]
    >>> reg='|'.join(oundary_words)
    >>> new_text=re.sub(reg,'',s).translate(None,punctuation)
    >>> new_text
    ' is224  ths'
    

    【讨论】:

    • 谢谢你的回答,但是做 s="this is a good way to another place" w=['this','a'] reg='|'.join() new_text= re.sub(reg,''s) 输出“is good wy to other plce”并从其他词中删除“a”。我怎么能只在它一个人的时候删除它?
    • @enderub 你需要把你的话放在一个词的边界上!结帐编辑!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    相关资源
    最近更新 更多