Catalog
  1. 1. 题目
  2. 2. 项目简介
  3. 3. 功能描述
  4. 4. 代码清单
数据结构课程设计实验三

题目

单词检索统计程序

项目简介

给定一个文本文件(见文后注意事项),要求统计给定单词在文本中出现的总次数,并检索输出某个单词出现在文本中的行号、在该行中出现的次数以及位置。

功能描述

使用者可创建自己命名的.txt文件,并写入其内容;还可以输入搜索的词并查找其出现次数、行号和所在的句子。

代码清单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import re
import sys
from string import punctuation

def create_file(name, msg):
partial_path = "D:\\Program Files (x86)\\JetBrains\\PyCharm 2019.2.4\\MyCode\\date_structure\\"
full_path = partial_path + name + '.txt'
global full_name
full_name = full_path
file = open(full_path, 'w')
file.write(msg)
print("File created successfully\n")
print(full_name)

def run_query(wanted):
word_total = 0
for each in one_word_list:
if each == wanted:
word_total += 1

print('"{}" occurs {} times'.format(wanted, word_total))

line_number = 0
for line in text_list:
line_plain = re.sub(r'[{}]'.format(punctuation), '', line)
word_list = [word.lower() for word in line_plain.split()]
line_number += 1
if wanted in word_list:
print('\tline {}: {}'.format(line_number, text_list[line_number - 1]), end='')

if __name__ == '__main__':
while True:
print("1.create file\n2.count and locate\n3.quit\n")
choice = input("Please enter the choice number:\n")

if choice == "1":
name = input("Please enter the name of file:\n")
msg = input("Please enter the contents:\n")
create_file(name, msg)

elif choice == "2":
wanted = input("Please enter the word:\n")
text = open(full_name, 'r')
text_list = text.readlines()
text_plain = re.sub(r'[{}]'.format(punctuation), '', ''.join(text_list))
one_word_list = [word.lower() for word in text_plain.split()]
print(one_word_list)
run_query(wanted)
print("\n")

else:
print("Thanks for using!\nBye~")
sys.exit(0)
Author: Christopher Shen
Link: https://www.pasxsenger.com/2020/03/13/数据结构课程设计实验三/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶