【问题标题】:Using replace() to remove full sentences from text data in Python [duplicate]使用 replace() 从 Python 中的文本数据中删除完整句子 [重复]
【发布时间】:2022-01-18 14:39:42
【问题描述】:

我正在尝试从文本数据段落中删除三个句子。我有一个 pandas 数据框,其中包含我想从中删除相同的三个句子的段落行。例如,

import pandas as pd

df_1 = pd.DataFrame({"text": ["the dog is red. He goes outside and runs.", 
                              "i like dogs because they are fun. i don't like that dogs bark at mailmen", 
                              "dogs bark at mailmen and i think its funny."]})
    
custom_stopwords = ["the dog is red", "i like dogs", "dogs bark at mailmen"]
 
for i in custom_stopwords: 
    df_1['text'] = df_1['text'].str.replace(i, '')

此方法在我提供的示例中有效,但不适用于我的实际数据。我拥有的数据非常大,但我不明白为什么在这种情况下这很重要。正在发生的事情是我的一些句子将被删除,而另一些则不会。例如,我无法删除单词“installation(s)”而不用“/”挡住括号。

【问题讨论】:

    标签: python pandas text replace str-replace


    【解决方案1】:

    pandas.Series.str.replace 具有regex=True 的默认关键字参数,这意味着它假定替换是正则表达式(就像您的“安装”可以被解释)。您正在尝试替换字符串文字(或至少是非常规表达式)。添加regex=False 应该可以正常工作:

    for i in custom_stopwords: 
        df_1['text'] = df_1['text'].str.replace(i, '', regex=False)
    

    【讨论】:

    • 谢谢,效果很好!我希望我早点问,而不是旋转我的轮子……几个小时!
    【解决方案2】:

    str.replace 与参数regex=False 一起使用。 (s) 被解释为一个正则表达式组,在这种特定情况下等于字符 s

    【讨论】:

    • 谢谢,效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2011-10-16
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多