【发布时间】:2014-10-13 23:41:22
【问题描述】:
我有一段写好的代码,
class Corpus:
def __init__(self):
return self
def __iter__(self):
return self
def __next__(self):
return self
def getwords():
pass
if __name__ == "__main__":
texts = []
if len(sys.argv) >= 2:
for filename in sys.argv[1:]:
texts.append(str(filename))
else:
print("Error!", sys.stderr())
removables = [".", ",", "!", "?", "(", ")"]
text = ""
for filename in texts:
with open(filename) as f:
for line in f:
text += line
words = text.lower().split()
allwords = {}
for word in words:
for removable in removables:
if removable in word:
word = word.replace(removable, "")
if word in allwords:
allwords[word] += 1
else:
allwords[word] = 1
print(allwords)
wordsearch = input("Enter word to search : ")
filesearch = input("Enter file to search in: ")
with open(filesearch) as f2:
for line in f2:
if wordsearch in line:
print(line)
wordsunique = len(allwords)
wordtotal = len(words)
filetotal = len(texts)
print("Total number of words: ", wordtotal)
print("Total number of unique words: ", wordsunique)
print("Total number of files: ", filetotal)
这是一个简单的单词计数器。但是,我宁愿将确定要搜索的文件名和单词的部分放入一个类中,以便代码可重用于我正在处理的更大项目。谁能指出我正确的方向?
【问题讨论】:
标签: python class code-reuse reusability