Skip to content

04030: 统计单词数

string, http://cs101.openjudge.cn/practice/04030

一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数。 现在,请你编程实现这一功能,具体要求是:给定一个单词,请你输出它在给定的文章中出现的次数和第一次出现的位置。注意:匹配单词时,不区分大小写,但要求完全匹配,即给定单词必须与文章中的某一独立单词在不区分大小写的情况下完全相同 (参见样例 1) ,如果给定单词仅是文章中某一单词的一部分则不算匹配(参见样例 2) 。

输入

第 1 行为一个字符串,其中只含字母,表示给定单词; 第 2 行为一个字符串,其中只可能包含字母和空格,表示给定的文章。

输出

只有一行, 如果在文章中找到给定单词则输出两个整数, 两个整数之间用一个空格隔开,分别是单词在文章中出现的次数和第一次出现的位置(即在文章中第一次出现时,单词首字母在文章中的位置,位置从 0 开始) ;如果单词在文章中没有出现,则直接输出一个整数-1。

样例输入

样例 #1:
To 
to be or not to be is a question 

样例 #2:
to 
Did the Ottoman Empire lose its power at that time

样例输出

样例 #1:
2 0

样例 #2:
-1

提示

【输入输出样例 1 说明】 输出结果表示给定的单词 To 在文章中出现两次,第一次出现的位置为 0。

【输入输出样例 2 说明】 表示给定的单词 to 在文章中没有出现,输出整数-1。

【数据范围】 1 ≤单词长度≤10。 1 ≤文章长度≤1,000,000。

2021fall-cs101,陈勇。这道题需要先在语句两头加“ ”进行保护,然后用“ ”+关键词+“ ”进行搜素。

python
string = ' ' + input().lower() + ' '
sentence = ' ' + input().lower() + ' '
loc = sentence.find(string)
if loc < 0:
    print(-1)
else:
    pro_stc = sentence.split()
    print(pro_stc.count(string[1:-1]), loc)

2021fall-cs101,吉祥瑞。注:

(1)第3行,前后加空格是一种巧妙的方法。 (2)第7行,单词总数不能用(' '+article+' ').count(' '+word+' ') 来求,例如,' a a '.count(' a ') 的结果是1而不是2,因为在计入第1个' a ' 后,就只剩下'a ' 了。 (3)样例输入首行的末尾有多余的空格,直接复制样例输入会使程序报错。 易错点:文章中单词之间可能有多个空格。

python
word = input().lower()
article = input().lower()
first = (' '+article+' ').find(' '+word+' ')
if first == -1:
    print(-1)
else:
    print(article.split().count(word), first)

2021fall-cs101,吉祥瑞。直接做,纯属练习。

python
word = input().lower()
article = input().lower()
e = tot = 0
while e < len(article):
    s = e
    while s < len(article) and article[s] == ' ':
        s += 1
    e = s
    while e < len(article) and article[e] != ' ':
        e += 1
    if article[s:e] == word:
        tot += 1
        if tot == 1:
            first = s
if tot == 0:
    print(-1)
else:
    print(tot, first)
python
import re

word = input().lower()
article = input().lower()

a = re.findall(r'\b'+word+r'\b', article)
cnt = len(a)
if cnt == 0:
    print(-1)
else:
    aa  = re.search(r'\b'+word+r'\b', article)
    print(cnt, aa.start())

2021fall-cs101, 叶晨熙。

注:title()使每个单词都首字母大写、其余字母小写,这样只需在后面补空格,并且可以直接用count()计数。

python
w = input().title() + ' '
s = input().title() + ' '
print([-1, str(s.count(w)) + ' ' + str(s.find(w))][s.count(w) != 0])