Python模拟英文打字练习的判分功能,文件“in.txt”中包含两段文字,第一段为原文,第二段为用户练习打字时输入的文字。编写程序统计打字练习时,大写字母,小写字母,数字字符以及其他字符的正确率,以及总正确率,正确率保留1位小数。如果某类字符的出现次数为0则正确率显示为100.0%
时间: 2024-03-09 08:51:03 浏览: 64
好的,下面是实现该功能的Python代码:
```python
# 打开文件
with open('in.txt', 'r') as f:
original_text = f.readline().strip()
user_input = f.readline().strip()
# 统计各类字符的出现次数
upper_count = 0
lower_count = 0
digit_count = 0
other_count = 0
correct_count = 0
for i in range(len(original_text)):
if original_text[i] != user_input[i]:
continue
correct_count += 1
if original_text[i].isupper():
upper_count += 1
elif original_text[i].islower():
lower_count += 1
elif original_text[i].isdigit():
digit_count += 1
else:
other_count += 1
# 计算正确率
total_count = len(original_text)
if total_count == 0:
upper_accuracy = 100.0
lower_accuracy = 100.0
digit_accuracy = 100.0
other_accuracy = 100.0
total_accuracy = 100.0
else:
upper_accuracy = round(upper_count / total_count * 100, 1)
lower_accuracy = round(lower_count / total_count * 100, 1)
digit_accuracy = round(digit_count / total_count * 100, 1)
other_accuracy = round(other_count / total_count * 100, 1)
total_accuracy = round(correct_count / total_count * 100, 1)
# 输出结果
print(f"大写字母的正确率为{upper_accuracy}%")
print(f"小写字母的正确率为{lower_accuracy}%")
print(f"数字字符的正确率为{digit_accuracy}%")
print(f"其他字符的正确率为{other_accuracy}%")
print(f"总正确率为{total_accuracy}%")
```
这段代码首先打开文件“in.txt”,读取原文和用户输入的文字。然后通过比较原文和用户输入的文字,统计各类字符的出现次数和总正确次数。最后根据总字符数和各类字符的出现次数,计算出正确率并输出结果。
注意,如果原文的字符数为0,则所有正确率都应该显示为100.0%。
阅读全文