中英掺杂的一段代码,先用正则表达式筛选出英文单词,然后再放到字典里,为什么每次只统计最后一段的单词?
alist在for里
可是你没有用变量保存它
它最后只保留了最后一次执行的值
import turtle as t
t.speed(0)
t.pensize(1)
t.pencolor('red')
t.setup(800, 800)
# 设置填充
t.fillcolor('red')
t.begin_fill()
# 到起始位置
t.up()
t.goto(0, 100)
t.down()
# 画左半边
t.left(135)
t.fd(120)
t.left(45)
t.fd(100)
t.left(45)
t.fd(100)
t.left(45)
t.fd(90)
t.left(45)
t.goto(0,-240)
# 抬起画笔变换位置
t.up()
t.goto(0, 100)
t.left(90)
t.down()
t.fd(120)
# 画右半边
t.right(45)
t.fd(100)
t.right(45)
t.fd(100)
t.right(45)
t.fd(90)
t.right(45)
t.goto(0,-240)
t.end_fill()
t.pencolor('white')
t.pensize(8)
t.up()
t.goto(-160, 20)
t.down()
# "I"
t.left(135)
t.fd(60)
t.back(30)
t.right(90)
t.fd(80)
t.right(90)
t.fd(30)
t.back(60)
# "L"
t.left(180)
t.up()
t.fd(50)
t.down()
t.left(90)
t.fd(80)
t.back(80)
t.right(90)
t.fd(35)
# 调整位置
t.up()
t.fd(50)
t.left(90)
t.fd(20)
t.down()
# "O"
t.circle(22,-180)
t.back(33)
t.circle(22,-180)
t.back(33)
# 调整位置
t.up()
t.back(20)
t.right(90)
t.fd(40)
t.down()
# 画“V”
t.left(110)
t.fd(80)
t.back(80)
t.right(40)
t.fd(80)
# 调整位置
t.up()
t.right(70)
t.fd(15)
t.down()
# 画 “ E ”
t.fd(35)
t.back(35)
t.right(90)
t.fd(38)
t.left(90)
t.fd(35)
t.back(35)
t.right(90)
t.fd(38)
t.left(90)
t.fd(35)
# 调整位置
t.up()
t.setx(0)
t.back(30)
t.right(90)
t.fd(25)
t.down()
# 画 “U”
t.fd(55)
t.circle(34,180)
t.fd(55)
t.mainloop()
我需要看到您当前的代码才能确定问题所在。 但是,您可能需要在每个段落之间重置字典,这样可以确保每个段落都被正确地计数。在读取下一个段落之前,请尝试将字典清空,示例如下:
import re
word_dict = {}
with open('your_file.txt', 'r') as f:
for line in f:
if not line.strip():
# new paragraph, reset dictionary
word_dict = {}
continue
words = re.findall(r'\b\w+\b', line) # modify the regex pattern to fit your needs
for word in words:
if word.lower() in word_dict:
word_dict[word.lower()] += 1
else:
word_dict[word.lower()] = 1
# print the word count for the current paragraph
print(word_dict)
这将在每个新段落之前创建一个新的空字典,以保证每个段落都被正确地计数。如果这不是解决问题的关键,请提供当前的代码以获得更详细的建议。