2012-10-28 53 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感觉刺痛或什么...? :) –