首页 > 解决方案 > 如何使用熊猫检查csv文件中的特定字符

问题描述

我已经将一个 CSV 文件读入 pandas 数据框,并试图找到所有包含我正在寻找的单词的句子,并且当找到其中任何一个时,使用主 CSV 中的原始索引而不是新索引来打印它。这是我正在尝试的代码,但由于某种原因它给了我一个错误

lookfor = '[' + re.escape(",?!.:;'؛؛؟'-)(؛،؛«/") + ']'


tdata = pd.read_csv(fileinput, nrows=0).columns[0]
skip = int(tdata.count(' ') == 0)
tdata = pd.read_csv(fileinput, names=['sentences'], skiprows=skip)

newdata=tdata[tdata['sentences'].str.isin(lookfor)]

print (newdata)


#a sample set
-----------------------------

#hi, how are; you 
#im good thanks
#How ? Is live.
#good, what about ) you/
#my name is alex
#hello, alex how are you !
#im good!
#great news
#thanks!
-----------------------------

它返回此错误


newdata=tdata[tdata['sentences'].str.isin(pat)]
AttributeError: 'StringMethods' object has no attribute 'isin'

输入数据看起来像

在此处输入图像描述

我期待的输出是

在此处输入图像描述

标签: pythonpandasdataframe

解决方案


您可能想要“包含”方法,例如

df = tdata[tdata.sentences.str.contains(pat, regex=True, na=False)]

完整的代码应该是这样的;

lookfor = '[' + re.escape(",?!.:;'؛؛؟'-)(؛،؛«/") + ']'

tdata = pd.read_csv(fileinput, nrows=0).columns[0]
skip = int(tdata.count(' ') == 0)
tdata = pd.read_csv(fileinput, names=['sentences'], skiprows=skip)

tdata['row_index'] = 1
tdata['row_index'] = tdata['row_index'].cumsum()

filtered = tdata[tdata.sentences.str.contains(lookfor, regex=True, na=False)]
filtered.to_csv('./my_path.csv', index=False)

推荐阅读