现有文件test.txt,编写程序完成以下功能: 1、将所有单词的首字母、末字母变为大写,并写入新的文件newtest.txt; (60) 2、统计各单词的出现数量,把统计结果写入文件count.txt中。(40) 程序代码直接贴在下面答案中,生成的文件以附件形式上传。 test.txt文件内容如下: Experts on Wednesday called for nurturing more pediatric psychiatrists and improving awareness about mental health problems among parents and school staff to more promptly detect children in need of help. Tie Changle, a psychiatrist at China-Japan Friendship Hospital, said that around 17.5 percent of school children and adolescents age 6 to 16 suffer mental disorders, citing a study released in 2021. Mental illnesses such as attention deficit hyperactivity disorder, anxiety disorder, oppositional defiant disorder and depressive disorder are the most prevalent, he said. "Furthermore, less than one-fifth of young patients have access to proper treatment," he said during a news conference held ahead of annual International Children's Day, which falls on June 1. Tie said that a shortage of psychiatrists, particularly those specializing in diagnosing and treating pediatric disorders, remains a serious problem. In addition, common mistakes or misunderstandings seen in parents include rationalizing or disregarding typical symptoms, shunning the use of medications or dismissing the role of mental therapies.
时间: 2024-03-03 07:51:13 浏览: 19
```python
import re
# 读取文件
with open('test.txt', 'r') as f:
text = f.read()
# 将所有单词的首字母、末字母变为大写,并写入新的文件newtest.txt
with open('newtest.txt', 'w') as f:
# 使用正则表达式匹配单词
pattern = re.compile(r'\b\w+\b')
# 遍历匹配到的所有单词
for word in pattern.findall(text):
# 将单词的首字母、末字母变为大写
new_word = word[0].upper() + word[1:-1] + word[-1].upper()
# 将新单词写入新文件中
f.write(new_word + ' ')
# 统计各单词的出现数量,把统计结果写入文件count.txt中
with open('count.txt', 'w') as f:
# 使用正则表达式匹配单词
pattern = re.compile(r'\b\w+\b')
# 将所有单词转换为小写,方便统计
words = [word.lower() for word in pattern.findall(text)]
# 统计每个单词出现的次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 将统计结果写入文件中
for word, count in word_count.items():
f.write(word + ': ' + str(count) + '\n')
```
生成的文件已上传至附件中。