从动态输入lin解析python

2024-04-20 02:08:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试一个程序,用模糊比率打印“好”字。一旦我得到行,它就必须拆分并打印下一行word:my program 没有得到输出

with open("qwer.txt",'r') as v1:
  for line in v1: 
    if 'good' in v1:
       print(v1)   
    if '=' in v1:    
       print v1.split('=')[1]

    if '==' in v1:
        print v1.split('==')[1]

qwer.txt文件:

Ram is very good=ideal student
Ram has nice character==Perfect student

输出:

Ram is very good=ideal student
ideal

一旦提供了语句,它就不执行了,请帮我获取输出


Tags: in程序txtifisstudentveryram
1条回答
网友
1楼 · 发布于 2024-04-20 02:08:40

您正在测试例如'=='是否是in v1不是line。尝试:

with open("qwer.txt",'r') as v1:
  for line in v1: 
    if 'good' in line: # note 'line' from here on in
       print(line)   
    if '=' in line:    
       print line.split('=')[1]
    if '==' in line:
        print line.split('==')[1]

这给了我:

Ram is very good=ideal student

ideal student


Perfect student

您还应该记住,您的'='条件并不是相互排斥的;如果'=='line中,那么'='也是。最好是这样:

with open("qwer.txt",'r') as v1:
  for line in v1: 
    if 'good' in line: # note 'line' from here on
       print(line)   
    if '==' in line: # '==' first   
       print line.split('==')[1]
    elif '=' in line: # 'elif', not just 'if' 
        print line.split('=')[1]

相关问题 更多 >