【问题标题】:python keyword search in csv commentscsv评论中的python关键字搜索
【发布时间】:2021-08-18 05:11:36
【问题描述】:

我正在尝试在列 cmets 中的 csv 文件中进行多个关键字搜索。出于某种原因,当我尝试搜索时,我收到此错误消息 'DataFrame' object has no attribute 'description'

例如

table1.csv
id_Acco,     user_name,       post_time      comments     
1543603,     SameDavie ,      "2020/09/06"   The car in the house  
1543595,     Johntim,         "2020/09/11"   You can filter the data
1558245,     ACAtesdfgsf ,    "2020/09/19"   if you’re looking at a ship 
1558245,     TDRtesdfgsf ,    "2020/09/19"   you can filter the table to show 

输出

id_Acco,     user_name,       post_time      comments     
1543603,     SameDavie ,      "2020/09/06"   The car in the house  
1543595,     Johntim,         "2020/09/11"   You can filter the data
1558245,     TDRtesdfgsf ,    "2020/09/19"   you can filter the table to show 

代码

df = pd.read_csv('table1.csv')
df[df.description.str.contains('house| filter | table | car')]
df.to_csv('forum_fraud_date_keyword.csv')

【问题讨论】:

  • 很高兴您选择了适合您的答案!也请考虑upvote the answer(现在你有 15 名声望并且应该能够投票)。谢谢!

标签: python pandas csv search


【解决方案1】:

您可以使用以下代码通过.str.contains()使用正则表达式进行过滤

df = df.loc[df.comments.str.contains(r'\b(?:house|filter|table|car)\b')]

在这里,我们使用 r-string 来包含正则表达式元字符。

我们使用\b 来包含 4 个目标词,这样它就只会匹配整个词而不是部分字符串。例如。 carmen 不会匹配 cartablespoon 不会匹配 table。如果要匹配部分字符串,可以去掉上面正则表达式中的\b对。

您可以查看此Regex Demo 以获得匹配的演示。

结果:

print(df)


   id_Acco,     user_name,     post_time                          comments
0  1543603,    SameDavie ,  "2020/09/06"              The car in the house
1  1543595,       Johntim,  "2020/09/11"           You can filter the data
3  1558245,  TDRtesdfgsf ,  "2020/09/19"  you can filter the table to show

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2019-08-23
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多