【发布时间】:2014-03-18 23:09:55
【问题描述】:
这个程序的目的是读入一个文件,把所有的单词变成单独的标记,然后把这些标记放到一个数组中。然后程序会删除所有标点符号并将所有字母更改为小写。然后程序应该计算每个命令行参数在数组中出现的次数,并打印结果。我的程序能够成功创建一个不带标点符号的小写标记数组。我现在的问题是如何遍历数组并计算特定单词的出现次数,以及我应该如何在主函数中调用这些函数。我的 depunctuate 函数按书面方式工作
这是我的程序:
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="""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
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()
【问题讨论】:
-
乍看之下,与your previous question相比,您似乎并没有自己完成任何工作。你拿了那里给你的代码,然后问如何添加它来解决你的下一个家庭作业。如果这不准确,你真的应该阅读MCVE(正如我上次告诉你的那样),并给我们一个重点示例,只展示你需要编写的部分、到目前为止你尝试过的内容以及你在哪里得到的卡住了。
-
你是对的。对于那个很抱歉。阅读 MCVE 并删除此问题。
标签: python arrays loops python-3.x