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

我只想输出长度为 5 且包含字符 p 的行。到目前为止

  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

有人猜吗?

4

1 回答 1

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
于 2012-10-28T08:02:44.880 回答