簡體   English   中英

使python輸入搜索功能不區分大小寫

[英]Making python input search function case insensitive

我正在創建一個接受用戶輸入的python 3搜索功能。 用戶輸入一個字符串,然后在單詞文檔中對其進行搜索。

我已經用2個docx文件測試了該功能-一個文件中帶有單詞“ hello”,另一個文件中帶有“ There”。

當我輸入正確大小寫的單詞(如docx文件中的單詞)時,搜索功能將返回文件名-成功! 但是,當我輸入沒有正確大小寫的單詞時,我什么也得不到。

我在這里看到了一些關於不區分大小寫的選項的問題,但是我找不到與我的項目足夠相似的選項。 任何幫助將非常感激。

import os
import docx2txt

os.chdir('c:/users/Says/desktop/projectx')

path = ('c:/users/Says/desktop/projectx')

files = []

x = str(input("search: "))

for file in os.listdir(path):
    if file.endswith('.docx'):
        files.append(file)

for i in range(len(files)):
    text = docx2txt.process(files[i])
    if x in text:
        print (files[i])

您可以使用.lower()使兩個字符串都變為小寫。

if x.lower() in text.lower():
    print( files[i] )

我可以建議的一種方法是將x轉換並testupperlower ,然后進行如下比較,它將為您提供所需的結果。

if x.upper() in text.upper():

if x.lower() in text.lower():

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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