2013-02-26 112 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']