簡體   English   中英

如何使用pandas檢查csv文件中的特定字符

[英]how to check for specific characters inside csv file using pandas

我已將一個 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'

輸入數據看起來像

在此處輸入圖片說明

我期待的輸出是

在此處輸入圖片說明

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

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM