从文本文件(Python)中的行读取特定字符

时间:2012-10-28 07:57:46

标签: python

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

我想只输出长度= 5且包含字符p.So far

的行
  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

有人猜吗?

1 个答案:

答案 0 :(得分: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
相关问题