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

我想获取单词的值,例如,如果用户输入句子并且它包含单词able,而不是像9 6 0or那样检索对它的值0 6 9,但是现在作为示例,我只希望如果我只关注其中的able#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
for line in file:
    print line.split()[:3]

您将获得每行的前三个元素,例如 ['0', '6', '9']。

如果你想按单词查找这 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 回答
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

如果数字之间只需要一个空格,请使用以下命令:

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 回答