[英]Python program to match string based on user input
我需要编写一个python程序,该程序允许用户输入Apple,Ball
类的输入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
Output:
Apple
Doll
您可以将循环更改为:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.