- 统计出给定文本的词频,找出词频最高和最低的单词;
2)找出给定文本中“Jit”出现的次数(不分大小写);
3)将给定文本中段落进行反向输出,并形成新的文本文件。
4)判断给定文本中第二段文本是否符合单词首字母大写,其余之母小写。如果不符合请转换输出到"学号".txt文件中
5)使用re.match()函数在给定文本中找出是否存在连续大于等于4个字母大写的字符串,请输出。
6)使用re.sub()函数实现给定文本中的“Nanjing”替换为Beijing",并输出。
import re
# 读取文件
with open('jit_introduction.txt', 'r', encoding='utf-8') as f:
data = f.read()
# 代替文件中特殊字符
data2 = data.replace('(', ' ').replace(')', ' ').replace('.', ' ').replace(',', ' ').replace('\n', ' ')
wordList = data2.split(' ')
while '' in wordList:
wordList.remove('')
# 字典储存单词
dict1 = {}
for word in wordList:
if word not in dict1:
dict1[word] = 1
else:
dict1[word] += 1
# 查找单词出现频率,输出最高、最低
wordList2 = sorted(dict1.items(), key=lambda word: word[1])
print('词频最高的单词:', wordList2[-1][0])
print('词频最低的单词:', wordList2[0][0])
# 查找jit出现的次数
sum0 = 0
for word in dict1:
if word.lower() == 'jit':
sum0 += dict1[word]
print('“Jit”出现的次数:', sum0)
# 打开新的文件,将给定文本中段落进行反向输出
paragraphList = data.split('\n')
paragraphList_reverse = paragraphList[::-1]
with open('new.txt', 'w', encoding='utf-8') as f:
for paragraph in paragraphList_reverse:
f.write(paragraph)
f.write('\n')
# 判断给定文本中第二段文本是否符合单词首字母大写,其余之母小写
while '' in paragraphList:
paragraphList.remove('')
paragraph_second = paragraphList[1]
if paragraph_second.istitle():
print('符合!')
else:
print('不符合!')
words = paragraph_second.split(' ')
paragraph_new = ''
for word in words:
paragraph_new += word[0].upper() + word[1:].lower() + ' '
with open('2012011131.txt', 'w', encoding='utf-8') as f:
f.write(paragraph_new)
f.write('\n')
# 使用re.match()函数在给定文本中找出是否存在连续大于等于4个字母大写的字符串
query = re.match('.*([A-Z]{4,})', data, flags=re.DOTALL)
if query is not None:
print('存在:' + query.group(1))
else:
print('不存在!')
# 使用re.sub()函数实现给定文本中的“Nanjing”替换为Beijing"
replace = re.sub('Nanjing', 'Beijing', data)
print(replace)