2012-10-28 56 views
0
char1= "P" 
length=5 
f = open("wl.txt", 'r') 

for line in f: 
if len(line)==length and line.rstrip() == char1: 
    z=Counter(line) 
    print z 

讀取線specfic角色,我想只輸出線,其中長度= 5和包含字符p.So遠從文本文件(Python)的

f = open("wl.txt", 'r') 
    for line in f: 
    if len(line)==length :#This one only works with the length 
     z=Counter(line) 
     print z 

任何猜測別人?

回答

5

您的問題是:

if len(line)==length and line.rstrip() == char1: 

如果行是5個字符長,然後除去尾隨空格之後,你再對比看看它是否等於長度爲1的串......「ABCDE '永遠不會等於'p',例如,如果你的行包含'p',因爲它不是5個字符,你的支票將永遠不會運行...

我不確定你想要做什麼Counter

更正後的代碼是:

# note in capitals to indicate 'constants' 
LENGTH = 5 
CHAR = 'p' 

with open('wl.txt') as fin: 
    for line in fin: 
     # Check length *after* any trailing whitespace has been removed 
     # and that CHAR appears anywhere **in** the line 
     if len(line.rstrip()) == LENGTH and CHAR in line: 
      print 'match:', line 
+0

本來應該想到你會對案例:) +1 – RocketDonkey

+0

你的解決方案有效,但匹配:不包含字符p。只有檢索的長度是5;我希望它檢索那些含有值p以及和我過檢查的文件存在具有角色P文本 即 比賽:他們\t 匹配:有\t 匹配:這些\t 比賽:價格\t 匹配:狀態 沒關係的伴侶,我覺得它工作非常感謝:) – user1780454

+0

@RocketDonkey我的spiderpig感覺刺痛或什麼...? :) –