2016-02-06 194 views
-4

我想知道如何在文本文件中找到一個特定的詞,而無需使用模塊re。 這是我當前的代碼:如何在文本文件中查找特定單詞?

searchfile = open("Menu.txt", "r") 
myList = [] 
cho = input("What cusine would you like to view the menu for") 


for line in searchfile: 
    myList.append(line+"\n") 

splitted_line = line.split(',') 
print(splitted_line[0]) 
indian = (myList[0]) 
mexican = (myList[1]) 
italian = (myList[2]) 

if 'mexican' in cho: 
    print(mexican) 
elif 'indian' in cho: 
    print(indian) 
elif 'italian' in cho: 
    print(italian) 


searchfile.close() 

cho2 = input("Would you like to order now or wait till later") 
if cho2 == 'now': 
    import practiseassessment.py 

if cho2 == 'later': 
    print("Ok for more information contact hungry horse at 07969214142") 

這是文本文件:

lamb curry , indian , chicken curry , indian vegtable curry , indian 
tacos , mexican fajitas , mexican nachos , mexican 
margherita pizza , italian vegetable pizza , italian bbq chicken pizza , italian 

我想在cho == indian僅打印印度菜。 我希望文本文件是每個菜的新行

+0

你需要編寫你自己的代碼或者是你讓3個項目使用例如'csv'模塊,甚至是'pandas'? – albert

+0

@albert自己寫代碼 –

+1

所以不允許使用'csv'?處理數據爲csv格式的數據會使事情變得相當容易。 – albert

回答

-1

這是解決這個問題的方法之一。正如你所看到的,你可以用python的內建字符串來完成所有的事情。

請注意,使用str.lower().strip()來標準化搜索項和菜單項,然後再比較它們。這將帶來更多的慷慨結果,並且不會懲罰用戶輸入額外的空間,而且通常是一件好事。

# First parse you input file and create the menu list 
with open("food.txt", "r") as foodfile: 
    menu_items = ' '.join(foodfile.readlines()).strip().split(',') 
menu_items = [item.strip() for item in menu_items] 

# menu_items is now the list ['lamb curry', 'indian', 'chicken curry' ... etc 

# I made the next part into a loop, so you can test several search terms. 
# instead of searching on user input, you can split the menu into several lists 
# but in most real world cases that is not really useful. With this approach 
# users can search for "pizza" or "chicken" in addition to "mexican", "italian" etc. 

while True: 
    cho = input("What cusine would you like to view the menu for? ").lower().strip() 
    if not cho: 
     break # break the loop if user submits an empty search string 
    search_results = [food for food in menu_items if cho in food.lower()] 
    print('\nFound %d items on the meny matching "%s"' % (len(search_results), cho)) 
    print(', '.join(search_results)) 

print('\ngoodbye') 

輸出示例:

你想什麼料理查看菜單呢? 印度

找到3項匹配「印度」印度,印度vegtable 咖喱,印度的玉米餅

你喜歡什麼料理查看菜單的MENY? 墨西哥

找到3項匹配「墨西哥」墨西哥捲餅的MENY,墨西哥玉米片 ,墨西哥瑪格麗特披薩

你喜歡什麼料理查看菜單呢?比薩餅

發現了MENY匹配「比薩」墨西哥瑪格麗特披薩, 意大利蔬菜披薩,意大利燒烤雞肉比薩

+0

它可以工作,但用戶應該能夠鍵入像這樣的句子「我想要意大利語」的「我可以買一些意大利語」,所以它應該在輸入中查找關鍵詞@Haken蓋 –

+0

你在原始問題中沒有提及。改爲發佈新問題。我對**自然語言處理**的經驗很少,這就是你需要解析輸入的東西。它是先進的東西。 –

-1

首先,我深入瞭解了您的數據,我認爲您忘記了一些逗號。所以我假設輸入數據如下所示:

lamb curry , indian , chicken curry , indian , vegtable curry , indian 
tacos , mexican fajitas , mexican nachos , mexican 
margherita pizza , italian , vegetable pizza , italian , bbq chicken pizza , italian 

有幾種方法可以獲得所需的輸出。但是,我僅使用stringlist操作,以避免使用其他Python模塊,如re。 我正在使用的唯一模塊是sys模塊,以便在由於列表長度不均勻而導致膳食和原點組合失敗時退出程序以中止執行。但是,通過使用適當的return語句編寫專用函數時,您可以擺脫此sys.ext()。所以這個解決方案能夠在沒有附加模塊的情況下工作。爲了展示這個想法,我認爲使用sys.exit()是可以的。

爲了進一步的說明,請參閱代碼中的註釋:

import sys 

with open('data.txt', newline='') as f: 
    data = f.readlines() 

stripped_data = [line.replace(' , ', ',') for line in data] 

# print in order to double check 
print(stripped_data) 

# write the whole data into a single string without newlines 
s = '' 
for line in data: 
    s += line.replace(' , ', ',').replace('\n', ',') 

# split string into several parts (which will be the meals and the origin)   
sliced = [e for e in s.split(',') if e] 

# print in order to double check 
print(sliced) 

# exit routine if list has uneven length since we would fail when trying to combine the pairs 
if len(sliced) % 2: 
    sys.exit('Uneven list length. Would fail to combine pairs.') 

# generate a list containing tuples of meal and origin --> (meal, origin)  
pairs = [(sliced[i], sliced[i+1]) for i in range(0, len(sliced), 2)] 

# ask the user what he wants to get served 
wanted = input('What do you want to have? ') 

# generate the output based on the user's input by accessing the tuples 
output = [i for i,k in pairs if k == wanted] 

# print the output 
print(output) 

with open('output.txt', 'w') as f: 
    for meal in output: 
     f.write('{}\n'.format(meal)) 

如果用戶希望indian飯菜輸出文件看起來是這樣的:

lamb curry 
chicken curry 
vegtable curry 
相關問題