python 在 csv 评论中搜索关键字
python keyword search in csv comments
我正在尝试在 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')
您可以使用以下代码通过 .str.contains()
使用正则表达式进行过滤
df = df.loc[df.comments.str.contains(r'\b(?:house|filter|table|car)\b')]
在这里,我们使用 r-string 来包含正则表达式元字符。
我们使用 \b
来包含 4 个目标词,这样它只会匹配整个词而不是部分字符串。例如。 carmen
不会与 car
匹配,tablespoon
不会与 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
我正在尝试在 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')
您可以使用以下代码通过 .str.contains()
df = df.loc[df.comments.str.contains(r'\b(?:house|filter|table|car)\b')]
在这里,我们使用 r-string 来包含正则表达式元字符。
我们使用 \b
来包含 4 个目标词,这样它只会匹配整个词而不是部分字符串。例如。 carmen
不会与 car
匹配,tablespoon
不会与 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