0
import re
sum=0
file = open("pro.txt").readlines()
for lines in file:
        word= len(re.findall('(^|[^\w\-])able#1(?=([^\w\-]|$))', lines))
        if word>0:
                sum=sum+1

pro.txt

0         6          9     able#1
0         11         34    unable#1
9         12         22    able#1
0         6          9     able#1-able#1
0         11         34    unable#1*able#1

単語の値を取得したいのですが、ユーザーが文を入力し、9 6 0または0 6 9のように値を取得するよりも可能な単語が含まれている場合のように、サンプルとして、可能な#1単語のみに焦点を当てる場合にそれが必要ですこのtxtファイルは、それを介して値を取得するにはどうすればよいですか

for lines in file:
    k=lines.split()
    print k


['0', '6', '9', 'able#1', 'you#1']
['0', '11', '34', 'unable#1']
['9', '12', '22', 'able#1']
['0', '6', '9', 'able#1-able#1']
['0', '11', '34', 'unable#1*able#1']
['9', '12', '22', 'able#1_able#1']

期待される出力:

enter the word you want to find in text file : able#1
word found !!
values are
0         6          9
4

2 に答える 2

0

どうぞ:

s = "able#1"

for line in open("pro.txt").readlines():
    if s == line.split()[3].strip():
        print line.rsplit(' ',1)[0].strip()

出力

>>> 
0         6          9
9         12         22

数字の間にスペースが1つだけ必要な場合は、次を使用します。

print ' '.join(line.split()[:3])

アップデート

完全なコード:

s = raw_input("enter the word you want to find in text file : ")

f = False
for line in open("pro.txt").readlines():
    if s == line.split()[3].strip():
        if not f:
            print "word found !!"
            f = True
        print ' '.join(line.split()[:3])

出力

>>> 
enter the word you want to find in text file : able#1
word found !!
0 6 9
9 12 22
>>> 
于 2013-02-26T18:08:32.127 に答える
0
for line in file:
    print line.split()[:3]

['0', '6', '9'] など、各行の最初の 3 つの要素を取得します。

単語ごとに 3 つの数字を調べたい場合は、最初にファイルの内容を使用して辞書を作成できます。

counts_by_word = dict((line[3], line[:3]) for line in file)
print counts_by_word["able#1"]
# Output: ['9', '12', '22']
于 2013-02-26T18:02:58.833 に答える