【问题描述】
“交叉引用生成器”(cross-refrencer)是指具有如下功能的程序:
对输入的一篇文档,统计出现的所有单词及其所在行号。将其结果以规定格式打印。
【输入形式】
程序从标准输入上读入一篇文档。该文档由若干行组成,每行中包含一系列单词。空行表示输入结束。
行号由1开始计数。该文档中单词总量不超过200,每个单词长度最大不超过20个字符。
【输出形式】
在标准输出上打印文档中所有出现的单词及其所在行号。
输出有若干行,每一行都是文档中出现的一个单词。按如下规格输出:
word:line1,line2,… ,lineN
其中word是单词,后面紧跟一个冒号,然后是以逗号隔开的出现行号line1,line2,等等。在该行上各字符紧密输出,不使用空格分隔。在输出时遵循以下规定:
-
只输出所有由英文字母(包括连字符)构成的单词,数字或包含其它特殊字符的单词不用输出。先输出大写A -Z开头的字符,再输出小写a-z开头的字符。
-
各单词后面的行号从小到大排列。行号不重复打印,亦即如果一个单词在一行内多次出现,则只打印一次该行号。
-
统计的单词不包括如下四个单词: a an the and
【样例输入】
Alcatel provides end-to-end solutions.
It enables enterprises to deliver content to any type of user.
lcatel operates in 130 countries.
Alcatel focus on optimizing their service offerings and revenue streams.
【样例输出】
Alcatel:1,4
It:2
any:2
content:2
countries:3
deliver:2
enables:2
end-to-end:1
enterprises:2
focus:4
in:3
lcatel:3
of:2
offerings:4
on:4
operates:3
optimizing:4
provides:1
revenue:4
service:4
solutions:1
streams:4
their:4
to:2
type:2
user:2
【样例说明】
输入一篇文档,输出文档中所有出现的单词及其所在行号。
import re
list_str = []
while True: # 读入行内容
try:
list_str.append(input())
except:
break
list_word = []
for i in range(len(list_str)):
list_str[i] = re.sub('[!-,.-@]', ' ', list_str[i]) # 去掉特殊字符、数字
list_word.append(list_str[i].split()) # 获取单个字符储存在二维数组中
dict_str = {}
for i in range(len(list_word)): # 字典储存
for j in list_word[i]:
# 判断不需要统计的单词
if j.lower() == 'a' or j.lower() == 'an' or j.lower() == 'the' or j.lower() == 'and':
continue
else:
# 单词储存在字典中
if j not in dict_str:
dict_str.setdefault(j, []).append(i + 1)
elif j in dict_str:
# 判断一行中出现两个相同的单词,只记录一次
if (i + 1) in dict_str.get(j):
continue
else:
dict_str.setdefault(j, []).append(i + 1)
# 字典key排序
dict_str = sorted(dict_str.items(), key=lambda x: x[0], reverse=False)
for key, value in dict_str:
if key == '-': # 因为 row 10-11 没有判断单个 ‘-’ ,会出现,在这里做个判断
continue
else:
print(key, end=':') # 输出键值
if len(value) > 1: # value长度大于一,要有 ‘,’ ,下面判断输出
t = 0
for i in value:
t += 1
print(i, end='')
if t != len(value):
print(',', end='')
else: # 直接输出value
for i in value:
print(i, end='')
print()
'''
Alcatel provides end-to-end solutions.
It enables enterprises to deliver content to any type of user.
lcatel operates in 130 countries.
Alcatel focus on optimizing their service offerings and revenue streams.
'''