2013-02-26 109 views
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如何使用python从文本文件中检索值?

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 00 6 9,但现在作为一个样本,我只是想,如果我在这个txt文件只专注于能#1字我怎样才能通过它检索值,因为我只是想它在某种程度上分裂,并不仅仅是把队列上

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 
+0

什么是您预期的输出? – ATOzTOA 2013-02-26 18:06:25

回答

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 
>>> 
+0

我想知道它,如果我发现价值面前的单词,所以首先它必须找到字,而不是价值观 – Rocket 2013-02-26 18:10:52

+0

你的输出是什么?你需要在#1中获得1吗? – ATOzTOA 2013-02-26 18:13:41

+0

没有,如果我想寻找能#1字在我的文本文件,如果那么这个词存在,它针对的是字 – Rocket 2013-02-26 18:16:20

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']