```c++
单词统计与检索程序
部分一:建立文本文件
用户通过键盘输入想要建立的文本文件名,并输入文本内容,程序将文本保存为用户指定的文件名。
python
filename = input("请输入要建立的文本文件名:")
text = input("请输入文本内容:")
with open(filename, 'w') as file:
file.write(text)
部分二:给定单词的计数
用户输入一个不含空格的单词,程序将该单词在文本中出现的总次数统计并输出。
python
filename = input("请输入要读取的文本文件名:")
word = input("请输入要计数的单词:")
count = 0
with open(filename, 'r') as file:
for line_num, line in enumerate(file, 1):
words = line.split()
for w in words:
if w == word:
count += 1
print(f"单词 {word} 在文本中共出现了 {count} 次。")
部分三:检索给定单词
用户输入一个单词,程序将该单词所在的行号、该行中出现的次数以及在该行中的相应位置检索并输出。
python
filename = input("请输入要读取的文本文件名:")
word = input("请输入要检索的单词:")
with open(filename, 'r') as file:
for line_num, line in enumerate(file, 1):
words = line.split()
word_count = words.count(word)
if word_count > 0:
print(f"单词 {word} 在第 {line_num} 行出现了 {word_count} 次,位置为:", end="")
for index, w in enumerate(words):
if w == word:
print(index+1, end=" ")
print()
以上就是单词统计与检索程序的实现
```