0

特定の文字列を含むテキスト ファイルの行を取得し、その行に 3 番目の数字または文字列を出力しようとしています。テキスト ファイルは次のようになります。

1997 180 60 bob

1997 145 59 dan

入力テキストに が含まれている場合bob、私のコードは を出力するはず60です。

これが私がこれまでに持っているものです:

calWeight = [line for line in open('user_details.txt') if name in line]
stringCalWeight = str(calWeight)
print (stringCalWeight)

どうすれば修正できますか?

4

3 に答える 3

1
with open('user_details.txt') as f:
    for line in f:
        if "bob" in line:
            print(line.split()[2]) 

ボブが行にあるすべての数値のリストが必要な場合は、リスト内包表記を使用します。

with open('user_details.txt') as f:
    nums =  [line.split()[2] for line in f if "bob" in line]

名前が行内の文字列の部分文字列である場合を避けたい場合は、確認する前に分割することもできます。たとえば、bob in bobbing-> True:

 nums =  [line.split()[2] for line in f if "bob" in line.split()]

より便利な構造は、値が各名前に関連付けられた行の 3 番目の数字すべてである dict だと思います。

from collections import defaultdict
d = defaultdict(list)
with open("in.txt") as f:
    for line in f:
        if line.strip():
           spl = line.rstrip().split()
           d[spl[-1]].append(spl[2])
print(d)
defaultdict(<type 'list'>, {'bob': ['60'], 'dan': ['59']})
于 2014-11-04T14:36:50.137 に答える
0
#need to open the file properly
with open('info.txt', 'r') as fp:
    #as suggested by @Padraic Cunningham it is better to iterate over the file object
    for line in fp:
        #each piece of information goes in a list
        infos = line.split()
        #this makes sure that there are no problems if your file has a empty line
        #and finds bob in the information
        if infos and infos[-1] == 'bob':
            print (infos[2])
于 2014-11-04T14:40:13.173 に答える