[英]Read text file line by line and Count specific word for particular values from a line and save the line above that
[英]Read a specific word from a text file and then save the next word
我需要從一個看起來像這樣的文本文件中讀取內容:
football 1
basketball 2
hockey 0
tennis 2
...
這里有x條線,每條線都有一項運動和一個數字。 我得到了一項運動,我不得不將該運動的數目保存在變量中,但是我找不到一種很好的方法來完成它。
這里有一些選擇。 最簡單的方法就是使用標准python遍歷文件對象。
# This will only get the first occurrence
with open("sportfile.txt", "r") as f:
for line in f:
curr_sport, num = line.split()
if curr_sport==sport:
break
如果出現多次,則可以將數字存儲在列表中-如果不需要特殊性,也可以將它們求和...取決於當前的問題。
sport = 'football' # for example
football_nums = []
with open("sportfile.txt", "r") as f:
for line in f:
curr_sport, num = line.split()
if curr_sport==sport:
football_nums.append(num)
有關python中文件句柄的信息,請參閱文檔“ https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files ”。
如果您需要將文件轉換為python結構,可以查詢以找到任何運動項目和相應的編號,那么您可以使用熊貓(可能會大材小用,但我喜歡熊貓:-)
df = pd.read_csv('sportfile.txt', sep = ' ')
df.columns = ['sport', 'num']
df[df.sport=='football'] # returns all rows where the sport is football.
pandas .read_csv()
瘋狂而詳盡且功能強大: http : .read_csv()
隨意嘗試。 剛剛在外殼中測試了快速樣本。
import sys
if __name__ == '__main__':
key = "football"
for line in sys.stdin:
sport, number = line.split()
if sport == key:
print "{}, {}".format(sport, number)
break
else:
print "{} not found".format(key)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.