繁体   English   中英

从文本文件中读取特定单词,然后保存下一个单词

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM