簡體   English   中英

如何查找包含用戶輸入的前3個字符的單詞

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM