Python 如何查找包含用户输入的前3个字符的单词
如何查找包含用户输入的前3个字符的单词。如果文件包含单词NYL000234和其他单词,并且用户提供类似NYL的输入,那么输出将是NYL000234 示例-文本文件包含-Python 如何查找包含用户输入的前3个字符的单词,python,Python,如何查找包含用户输入的前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
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
如果用户给出输入列,那么输出将如下。。
输出应为列而不是行
COL01139
COL01356
COL03031
COL03008
COL03050
COL03002
COL05067
COL03047
COL05077
COL03045
您可以使用正则表达式:
import re
results = re.findall('{}\d+'.format(input('enter root: ').upper()), open('filename.txt').read())
输入为col时的输出:
试试这个:
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)
您可以通过列表理解使其更具python风格,请尝试:[文件中的逐字逐行。行中的逐字逐行。如果word[:3],则拆分。lower==user\u letters.lower],而不是word[:3]。lower==user\u letters.lower,您只需使用word.lower.startswithuser_letters.lower请尝试自己解决此问题,并为我们提供一些代码来显示您的尝试!F1=openSR.txt,'r'代表F1行:line=line.strip.split代表word行:printword选项=输入名称=如果选项==word[:3]:printword F1.closeF1=openSR.txt,'r'代表F1行:line=line.strip.split代表word行:printword选项=输入名称=如果选项==word[:3]:printword F1.closeF1=openSR.txt,F1中的行的“r”:行=行.strip.split打印行F1。close@AlokGuptainput'enter root:'返回用户通过命令提示符输入的内容。
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)