首页 文章

Python程序根据用户输入匹配字符串

提问于
浏览
0

我需要编写一个python程序,允许用户输入像 Apple,Ball 这样的输入,如果匹配文件中的行打印它 . 到目前为止,我能够得到这个 .

import re
import sys
print('Enter the values')
value1=input()

try:
    filenm1="D:\names.txt"
    t=open(filenm1,'r')
    regexp=re.search(value1,line)
    for line in t:
        if regexp:
            print(line)
catch IOerror:
    print('File not opened')
sys.exit(0)

示例输入文件

Apple
Ball
Stackoverflow
Call
Doll

User input : App
Output : Apple

现在我想修改此程序以按用户输入搜索: App,Doll 输出:

Apple
Doll

1 回答

  • 0

    您可以将循环更改为:

    import sys
    print('Enter the values')
    value1=input()
    value1=value1.split(',')
    
    try:
        filenm1="D:\names.txt"
        t=open(filenm1,'r')
        for line in t:
            alreadyPrinted = False
            for value in value1:
                if value in line:
                    if not alreadyPrinted: #this bit prevents line being printed twice
                        print(line)
                        alreadyPrinted = True
    except IOerror:
        print('File not opened')
    sys.exit(0)
    

相关问题