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

时间:2016-10-03 09:18:32

标签: python python-3.x

我需要编写一个允许用户输入输入的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 :(得分: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)