[英]How to extract information from a string in Python?
我有一個csv文件,其中包含一個獎項列,其中包含各種不同的提名和獲獎情況。 我想從該dataset
的獎項列中提取數據,並將其拆分為幾列。 獎項包括獲勝,提名的詳細信息,以及某些類別(例如,奧斯卡,BAFTA等)的獲勝和提名。獎勵列的示例輸入如下所示。
我想將此數據分為幾個分析數據的列。 我們可以使用python實現嗎? 我正在使用熊貓來訪問dataframe
。 預期輸出示例如下所示。
看來您的數據結構不是特別好。 如果保證格式為以下格式:
x獲勝& y提名。
然后是下面的代碼:
testStrings = ['1 win & 1 nomination.','2 wins.','5 nominations.', '3 wins & 8 nominations.', '2 wins.','9 wins.']
text = [i.split('&') for i in testStrings]
data=[]
for row in text:
for t in row:
winIndex = t.find('win')
nomIndex = t.find('nom')
if winIndex>0:
w=int(t[:winIndex-1] )
else:
w=0
if nomIndex>0:
n=int(t[:nomIndex-1] )
else:
n=0
data.append([w,n])
將為您提供列表數據 ,其中每一行的每個元素為[numWins,numNoms] 。
您可以通過搜索那些關鍵字(例如代碼查找子字符串“ won”和“ nom”)將其擴展為應付不同格式(例如“ Won 1 Primetime Emmy”)。 希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.