2016-11-05 59 views
-8

我正在編寫一個Python腳本。我需要在一個文本文件中搜索以「s,es或ies」結尾的單詞,並且該單詞必須大於三個字母,需要識別單詞數量和單詞it-self .....這很難我無法使用它,請幫助我Python腳本搜索文本文件的一個詞

+0

*這是硬任務,我不能用它工作* - 再回去學習基礎知識和**實際學習**?要求我們爲你做這件事不會幫助你學到任何東西。 – Li357

+0

你有一個可重複的例子嗎?嘗試迭代文件的行並使用'if'語句返回您要查找的內容。 – Jakub

+0

看起來您希望我們爲您編寫一些代碼。儘管許多用戶願意爲遇險的編碼人員編寫代碼,但他們通常只在海報已嘗試自行解決問題時才提供幫助。展示這一努力的一個好方法是包含迄今爲止編寫的代碼,示例輸入(如果有),預期輸出以及實際獲得的輸出(控制檯輸出,回溯等)。您提供的細節越多,您可能會收到的答案就越多。檢查[FAQ](http://stackoverflow.com/tour)和[如何提問](http://stackoverflow.com/help/how-to-ask)。 –

回答

2

我同意評論,你需要去工作的基礎知識。這裏有一些想法讓你開始。

1)你說「搜索文件」。由線像這樣打開一個文件並讀取行:

with open ('myFile.txt', 'r') as infile: 
    for line in infile: 
     # do something to each line 

2)你可能想存儲在數據結構中的每一行,像一個列表:

# before you open the file... 
lines = [] 

# while handling the file: 
lines.append(line) 

3)你需要與每個詞一起工作。查看列表的「拆分」功能。

4)您需要查看每個單詞的單個字母。看看'字符串切片'。

說了這麼多,你可以用10-15行代碼來做到這一點。

0

嘗試將任務分成不同的任務,如果感覺壓倒性的。 以下代碼絕不是好事,但希望它足夠清晰,以便您明白。

1首先您需要獲取您的文本。如果您的文本位於您計算機的文件中,則需要將其放入python可以使用的內容中。

# this code takes the content of "text.txt" and store it into my_text 
with open("text.txt") as file: 
    my_text = file.read() 

2現在您需要處理每個單詞。你所有的單詞都被放在一個名爲my_text的字符串中,並且你希望它們分離(分割)成一個列表,以便你可以單獨使用它們。通常詞用空格隔開,所以這是你用什麼將它們分開:

# take the text and split it into words 
my_words = my_text.split(" ") 

3我並不確切地知道自己想要什麼,但是讓我們假設你要分開的話存儲在不同的列表。那麼你將需要這些列表:

# three list to store the words: 
words_s = [] 
words_es = [] 
words_ies = [] 

4現在你需要遍歷單詞,並與他們做的東西。爲實現這一目標最簡單的辦法是使用一個for循環:

#iterate through each word 
for word in my_words: 

    # you're not interested in short words: 
    if len(word) <= 3: 
     continue # this means: do nothing with this word 


    # now, if the word's length is greater than 3, you classify it: 

    if word.endswith("ies"): 
     words_ies.append(word) # add it to the list 

    if word.endswith("es"): 
     words_es.append(word) # add it to the list 

    if word.endswith("s"): 
     words_s.append(word)  # add it to the list 

4最後,外面的for循環,可以打印單詞列表,並獲取列表的長度:

print(words_s)  
print(len(words_s)) 

你需要考慮的是如果你想重複或不重複的話。請注意,以「s」,「es」或「ies」結尾的條件等同於以「s」結尾的詞。上面的代碼將冗餘地分配到不同列表中的單詞。如果一個單詞以「ies」結尾,它也以「es」和「s」結尾,所以它將被存儲在三個列表中。如果你想避免重疊,你可以用if語句替換if語句。

不斷學習的基礎知識爲其他答案建議,很快你就可以明白嚇人這樣的代碼:d

with open("text.txt") as myfile: 
    words = [word for word in myfile.read().split(" ") if word.endswith("s") and len(word) > 3] 
    print("There are {} words ending with 's' and longer than 3".format(len(words)))