該程序的目的是讀取文件,將所有單詞轉換爲單個令牌,並將這些令牌放入數組中。該程序然後刪除所有標點並將所有字母改爲小寫。然後程序應該計算每個命令行參數在數組中出現的次數,並打印結果。我的程序能夠成功創建一個已刪除小寫令牌的數組。我現在的問題是如何遍歷數組並計算特定單詞的出現次數,以及如何在主函數中調用這些函數。我depunctuate功能可以作爲書面計算數組中項目的出現python
這是我的計劃:
import sys
from scanner import *
def main():
print("the name of the program is",sys.argv[0])
for i in range(1,len(sys.argv),1):
print(" argument",i,"is", sys.argv[i])
tokens = readTokens("text.txt")
cleanTokens = depunctuateTokens(tokens)
words = [token.lower() for token in cleanTokens]
count = find(words)
print(words)
print(count)
def readTokens(s):
arr=[]
s=Scanner("text.txt")
token=s.readtoken()
while (token != ""):
arr.append(token)
token=s.readtoken()
s.close()
return arr
def depunctuateTokens(arr):
result=[]
for i in range(0,len(arr),1):
string=arr[i]
cleaned=""
punctuation="""!"#$%&'()*+,-./:;<=>[email protected][\]^_`{|}~"""
for i in range(0,len(string),1):
if string[i] not in punctuation:
cleaned += string[i]
result.append(cleaned)
return result
def find(tokens,words):
return occurences(tokens,words)>0
def occurences(tokens,words):
count = 0
for i in range(0,len(words),1):
if (words[i] == tokens):
count += 1
return count
main()
[我如何計算Python中的列表項的出現?](http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a- list-item-in-python) – isedev
乍一看,比較[你以前的問題](http://stackoverflow.com/questions/21842427/mapping-a-function-over-all-the-letters-of-a -token-in-python),它看起來並不像你自己做了任何工作。你拿到了在那裏給你的代碼,然後詢問如何添加它來解決你的下一個家庭作業。如果這不正確,你應該閱讀[MCVE](http://stackoverflow.com/help/mcve)(正如我上次所說的),並給我們一個集中的例子,它只演示你需要編寫的部分,你到目前爲止已經嘗試過,以及你卡在哪裏。 – abarnert
你說得對。對於那個很抱歉。生病讀了MCVE並刪除了這個問題。 – user3321218