[英]How to find words which contain the first 3 characters input by a user
如何查找包含用户输入的前3个字符的单词。 如果文件包含单词NYL000234和其他单词,并且用户提供了类似于NYL的输入,则输出将为NYL000234。
示例-文本文件包含-
10099834 COL01139 OD 1_1_2_1
T1 10115177 COL01356 OD 1_1_3_1
T1 10099848 COL03031 OD 1_1_2_1
T1 10093544 COL03008 OD 1_1_1_1
T1 10101126 COL03050 ID
1_1_2_1 10093697 COL03002 ID
1_1_3_1 10122993 COL05067 ID
1_1_2_1 10093668 COL03047 ID
1_1_2_1 10127012 COL05077 ID
1_1_3_1 10093664 COL03045 ID 1_1_2_1
如果用户提供输入COL,则输出将如下所示(输出应为列而不是行)
COL01139
COL01356
COL03031
COL03008
COL03050
COL03002
COL05067
COL03047
COL05077
COL03045
尝试这个:
with open("your_file.txt", "r") as file: ## Open file
lines = file.splitlines() ## Read the lines into a list
for line in lines: ## Loop through the lines
for word in line.split(): ## Loop through the words
if word.lower().startsWith(user_letters.lower()):
## If the word starts with the letters provided by the user
print(word)
您可以使用正则表达式:
import re
results = re.findall('{}\d+'.format(input('enter root: ').upper()), open('filename.txt').read())
输出(当输入为"col"
):
['COL01139', 'COL01356', 'COL03031', 'COL03008', 'COL03050', 'COL03002', 'COL05067', 'COL03047', 'COL05077', 'COL03045']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.