from pathlib import Path
def count(filename: str, word = "hello"):
file = Path(filename)
text = file.read_text()
lines_excluding_first = text.split("\n")[1:]
counts = sum([sum(list(map(lambda y: 1 if word == y else 0, x.split(" ")))) for x in lines_excluding_first])
return counts
例如:
假设您有一个txt文件,如:
sample.txt
this is the first line so this dose not count!
hello!! this is a sample text.
text which will be used as sample.
if nothing no word specified hellow is returned!
it will return the count.
def wordcount(filename, word="hello"):
# Open the file name
with open(filename) as file:
# Skip first line
next(file)
# read the file as a string except the first line and count the occurrences
return file.read().count(word)
Hello ! My name is João, i will repeat this !
Hello ! My name is João, i will repeat this !
Hello ! My name is João, i will repeat this !
Hello ! My name is João, i will repeat this !
Hello ! My name is João, i will repeat this !
例如: 假设您有一个txt文件,如:
编辑:
我已经在代码中做了一个小的修改}和“hellow.”也不同
"hellow!!"
和"hellow"
是两个独立的单词。单词之间用空格分隔,然后检查是否相等。因此{根据请求,这里是它在
repl.it
上的外观:首先制作一个sample.txt: main.py看起来像: 您可以看到默认“hello”的输出为2
[output is case sensitive i.e Hello and hello are not the same]
使用两个参数调用函数,一个文件名必须位于path中,另一个单词必须在文件中计数。如果不传递单词,函数将采用默认单词“hello”
Count方法返回给定字符串中子字符串的出现次数。如果你想以后使用它,你也可以保存第一行
x = next(file)
调用函数并用
print(wordcount("sample.txt", "repeat"))
打印结果,以计算单词“repeat”在文件中出现的次数sample.txt包含:
结果必须是4:)
相关问题 更多 >
编程相关推荐