Python 循环内迭代变量名
我几乎没有编程方面的实践经验,但我已经开始学习python,并希望创建一个函数来计算文本中最频繁的单词。现在,我确信我的版本不是最好的方法,但它可以工作:Python 循环内迭代变量名,python,loops,dictionary,turtle-graphics,Python,Loops,Dictionary,Turtle Graphics,我几乎没有编程方面的实践经验,但我已经开始学习python,并希望创建一个函数来计算文本中最频繁的单词。现在,我确信我的版本不是最好的方法,但它可以工作: import os punctuation = "~!@#$%^&*()_-=+[{]}\\|'\";:,<.>/?" def remove_punctuation(text): text_wo_punctuation = "" for word in text: if w
import os
punctuation = "~!@#$%^&*()_-=+[{]}\\|'\";:,<.>/?"
def remove_punctuation(text):
text_wo_punctuation = ""
for word in text:
if word not in punctuation:
text_wo_punctuation += word
return text_wo_punctuation
with open(r'New Text Document.txt') as f:
text = f.read().lower()
t = remove_punctuation(text).split()
dictionary = {}
for word in t:
if word in dictionary:
dictionary[word] = dictionary[word] + 1
else:
dictionary[word] = 1
print(dictionary)
def top_five(d):
top = {}
value1 = 0
value2 = 0
value3 = 0
value4 = 0
value5 = 0
for key in dictionary:
if value1 < dictionary[key] and key not in top:
value1 = dictionary[key]
top1 = {key:value1}
else:
continue
top.update(top1)
for key in dictionary:
if value2 < dictionary[key] and key not in top:
value2 = dictionary[key]
top2 = {key:value2}
else:
continue
top.update(top2)
for key in dictionary:
if value3 < dictionary[key] and key not in top:
value3 = dictionary[key]
top3 = {key:value3}
else:
continue
top.update(top3)
for key in dictionary:
if value4 < dictionary[key] and key not in top:
value4 = dictionary[key]
top4 = {key:value4}
else:
continue
top.update(top4)
for key in dictionary:
if value5 < dictionary[key] and key not in top:
value5 = dictionary[key]
top5 = {key:value4}
else:
continue
top.update(top5)
return top
print(top_five(dictionary))
这将在字典中创建一个字典。我被困在这一点上,因为我找不到使“top”字典有用的方法,也找不到在循环中迭代变量名的方法。我读过应该使用列表或字典,变量名迭代不是一个好主意,但我不明白为什么会这样,我想不出一种方法使列表或字典在for循环中有用
正如我所说的,我知道这可能不是制作此类函数的最佳方法,但我的问题是:如何简化我已经制作的函数并使循环工作
谢谢 我已根据Barmar的建议更新了代码:
def remove_punctuation(text):
""""Removes punctuation characters from given text"""
punctuation = "~`!@#$%^&*()_-=+[{]}\\|'\";:,<.>/?"
text_wo_punctuation = ""
for word in text:
if word not in punctuation:
text_wo_punctuation += word
return text_wo_punctuation
def count_words(file):
"""Returns a dictionary of words and word count from "file" """
with open(file) as f:
text = remove_punctuation(f.read()).lower().split()
dictionary = {}
for word in text:
# print(word)
if word in dictionary:
dictionary[word] = dictionary[word] + 1
# print("**Existing**")
else:
dictionary[word] = 1
# print("**New**")
# print(dictionary[word])
return dictionary
#print(dictionary)
def dict_sort(d, reverse = False):
"""Sort given dictionary "d" in ascending (default)
or descending (reverse = True) order
Outputs tuple of: list of keys, list of values and dictionary
Recommended format for output: a,b,c = dict_sort(d)"""
key_list = []
value_list = []
for key in d:
key_list.append(key)
value_list.append(d[key])
#print(key_list)
#print(value_list)
for i in range(len(value_list)-1):
for i in range(len(value_list)-1):
if reverse == False:
if value_list[i] > value_list[i+1]:
value_list[i],value_list[i+1] = value_list[i+1],value_list[i]
key_list[i],key_list[i+1] = key_list[i+1],key_list[i]
elif reverse == True:
if value_list[i] < value_list[i+1]:
value_list[i],value_list[i+1] = value_list[i+1],value_list[i]
key_list[i],key_list[i+1] = key_list[i+1],key_list[i]
d = {}
for i in range(len(value_list)):
d[key_list[i]] = value_list[i]
sorted_dict = d
return key_list,value_list,sorted_dict
def word_freq():
"""Input how many words to plot on graph"""
while True:
try:
n_freq = int(input("How many of the most frequent words would you like to display?\n"))
if (n_freq < 1 or n_freq > 10):
print("Please input an integer between 1 and 10:")
continue
except(ValueError):
print("Please input an integer between 1 and 10:")
continue
else:
break
return n_freq
def graph_word_freq(n,f,w): #create function to draw chart
"""Draw bar chart of most frequent words in text
n: number of words to plot (between 1 and 10)
f: word frequency list
w: word list"""
import turtle #import turtle module
window = turtle.Screen() #create screen
window.bgcolor("honeydew") #define screen color
window.title("Most Frequent Words") #set window title
if f[0] < 960:
y = 500
y_pos = -480
width = 60
spacing = 20
x_pos = -(30+40*(n-1))
else:
width = 100
spacing = 40
y = f[0]/2+20
y_pos = -f[0]/2
x_pos = -(50+70*(n-1))
#turtle.screensize(y,y) #set window size
turtle.setworldcoordinates(-y,-y,y,y)
tortoise = turtle.Turtle() #create turtle
tortoise.hideturtle() #hide turtle stamp
tortoise.penup() #raise turtle pen
tortoise.setposition(x_pos,y_pos) #position turtle
tortoise.pendown() #put turtle pen down
tortoise.speed(5) #set drawing speed
for i in range(n):
if abs(f[i]) < ((f[0]-f[n])/3):
tortoise.color("SeaGreen","ForestGreen") #set turtle color
elif abs(f[i]) >= ((f[0]-f[n])/3) and abs(f[i]) < ((f[0]-f[n])/1.5):
tortoise.color("orange","gold") #set turtle color
else:
tortoise.color("coral3","IndianRed") #set turtle color
tortoise.begin_fill() #begin drawing shapes
tortoise.left(90)
tortoise.forward(f[i]) #draw bar height
tortoise.right(90)
tortoise.forward(1/3*width) #prepare for text
if f[i] >= 0:
tortoise.write(f[i]) #write value
else:
tortoise.penup()
tortoise.right(90)
tortoise.forward(15)
tortoise.write(f[i])
tortoise.forward(-15)
tortoise.left(90)
tortoise.pendown()
tortoise.forward(2/3*width) #bar width
tortoise.right(90)
tortoise.forward(f[i])
tortoise.left(90)
tortoise.penup()
tortoise.right(90)
tortoise.forward(25)
tortoise.left(90)
tortoise.forward(-2/3*width)
tortoise.write(w[i]) #write word
tortoise.forward(2/3*width)
tortoise.left(90)
tortoise.forward(25)
tortoise.right(90)
tortoise.forward(spacing) #spacing
tortoise.pendown()
tortoise.end_fill() #stop drawing shapes
turtle.exitonclick()
dictionary = count_words("New Text Document.txt")
words,values,dictionary = dict_sort(dictionary, reverse = True)
n_freq = word_freq()
graph_word_freq(n_freq,values,words)
def删除标点符号(文本):
“”从给定文本中删除标点符号“”
标点符号=“~`@$%”^&*()_-=+[{]}\\|'\";:,/?"
text_wo_标点=“”
对于文本中的单词:
如果单词没有标点符号:
text\u wo\u标点符号+=单词
返回文本\u wo\u标点符号
def计数_字(文件):
“”“从“文件”返回单词词典和单词计数”
打开(文件)为f时:
text=删除标点符号(f.read()).lower().split()
字典={}
对于文本中的单词:
#打印(word)
如果字典中有单词:
字典[字]=字典[字]+1
#打印(“**现有**”)
其他:
字典[字]=1
#打印(“**新**”)
#打印(字典[单词])
返回字典
#印刷(字典)
def dict_排序(d,反向=False):
“”“对给定字典“d”进行升序排序(默认)
或降序(反向=真)顺序
输出元组:键列表、值列表和字典
建议的输出格式:a、b、c=dict_排序(d)”
键列表=[]
值_列表=[]
对于输入d:
键列表。追加(键)
value\u list.append(d[键])
#打印(按键列表)
#打印(值列表)
对于范围内的i(len(值列表)-1):
对于范围内的i(len(值列表)-1):
如果反向==假:
如果值列表[i]>值列表[i+1]:
值列表[i],值列表[i+1]=值列表[i+1],值列表[i]
键列表[i],键列表[i+1]=键列表[i+1],键列表[i]
elif reverse==真:
如果值列表[i]<值列表[i+1]:
值列表[i],值列表[i+1]=值列表[i+1],值列表[i]
键列表[i],键列表[i+1]=键列表[i+1],键列表[i]
d={}
对于范围内的i(len(值列表)):
d[键列表[i]]=值列表[i]
已排序的dict=d
返回键列表、值列表、排序目录
def word_freq():
“”“输入要在图形上打印的单词数”“”
尽管如此:
尝试:
n_freq=int(输入(“您希望显示多少最常用的单词?\n”))
如果(n_freq<1或n_freq>10):
打印(“请输入一个介于1和10之间的整数:”)
持续
除了(值错误):
打印(“请输入一个介于1和10之间的整数:”)
持续
其他:
打破
返回n_频率
def graph_word_freq(n,f,w):#创建用于绘制图表的函数
“”“绘制文本中最常用单词的条形图
n:要绘制的字数(介于1和10之间)
f:词频表
w:单词列表“”
导入海龟#导入海龟模块
window=turtle.Screen()#创建屏幕
window.bgcolor(“蜜露”)#定义屏幕颜色
window.title(“最常用词”)#设置窗口标题
如果f[0]<960:
y=500
y_pos=-480
宽度=60
间距=20
x_位置=-(30+40*(n-1))
其他:
宽度=100
间距=40
y=f[0]/2+20
y_pos=-f[0]/2
x_位置=-(50+70*(n-1))
#海龟。屏幕大小(y,y)#设置窗口大小
海龟。设置世界坐标(-y,-y,y,y)
乌龟=乌龟。乌龟()#创造乌龟
乌龟。藏身处()#隐藏乌龟邮票
乌龟,举起乌龟笔
乌龟。设置位置(x_位置,y_位置)#乌龟位置
乌龟,放下乌龟笔
乌龟。速度(5)#设定牵引速度
对于范围(n)中的i:
如果abs(f[i])<((f[0]-f[n])/3):
乌龟色(“海绿”、“森林绿”)#设置乌龟色
elif abs(f[i])>=((f[0]-f[n])/3)和abs(f[i])<((f[0]-f[n])/1.5:
乌龟色(“橙色”、“金色”)#设置乌龟色
其他:
乌龟色(“珊瑚色”、“印度红”)#设置乌龟色
乌龟。开始填充()#开始绘制形状
乌龟。左(90)
乌龟。前进(f[i])#牵引杆高度
乌龟。右(90)
乌龟。向前(1/3*宽)#准备文本
如果f[i]>=0:
乌龟。写入(f[i])#写入值
其他:
乌龟
乌龟。右(90)
乌龟。前进(15)
乌龟。写(f[i])
乌龟。前进(-15)
乌龟。左(90)
乌龟
乌龟。向前(2/3*宽)#杆宽
乌龟。右(90)
乌龟前进(f[i])
乌龟。左(90)
乌龟
乌龟。右(90)
乌龟。前进(25)
top["top"+str(i)] = {key:values["value"+str(i)]}
def remove_punctuation(text):
""""Removes punctuation characters from given text"""
punctuation = "~`!@#$%^&*()_-=+[{]}\\|'\";:,<.>/?"
text_wo_punctuation = ""
for word in text:
if word not in punctuation:
text_wo_punctuation += word
return text_wo_punctuation
def count_words(file):
"""Returns a dictionary of words and word count from "file" """
with open(file) as f:
text = remove_punctuation(f.read()).lower().split()
dictionary = {}
for word in text:
# print(word)
if word in dictionary:
dictionary[word] = dictionary[word] + 1
# print("**Existing**")
else:
dictionary[word] = 1
# print("**New**")
# print(dictionary[word])
return dictionary
#print(dictionary)
def dict_sort(d, reverse = False):
"""Sort given dictionary "d" in ascending (default)
or descending (reverse = True) order
Outputs tuple of: list of keys, list of values and dictionary
Recommended format for output: a,b,c = dict_sort(d)"""
key_list = []
value_list = []
for key in d:
key_list.append(key)
value_list.append(d[key])
#print(key_list)
#print(value_list)
for i in range(len(value_list)-1):
for i in range(len(value_list)-1):
if reverse == False:
if value_list[i] > value_list[i+1]:
value_list[i],value_list[i+1] = value_list[i+1],value_list[i]
key_list[i],key_list[i+1] = key_list[i+1],key_list[i]
elif reverse == True:
if value_list[i] < value_list[i+1]:
value_list[i],value_list[i+1] = value_list[i+1],value_list[i]
key_list[i],key_list[i+1] = key_list[i+1],key_list[i]
d = {}
for i in range(len(value_list)):
d[key_list[i]] = value_list[i]
sorted_dict = d
return key_list,value_list,sorted_dict
def word_freq():
"""Input how many words to plot on graph"""
while True:
try:
n_freq = int(input("How many of the most frequent words would you like to display?\n"))
if (n_freq < 1 or n_freq > 10):
print("Please input an integer between 1 and 10:")
continue
except(ValueError):
print("Please input an integer between 1 and 10:")
continue
else:
break
return n_freq
def graph_word_freq(n,f,w): #create function to draw chart
"""Draw bar chart of most frequent words in text
n: number of words to plot (between 1 and 10)
f: word frequency list
w: word list"""
import turtle #import turtle module
window = turtle.Screen() #create screen
window.bgcolor("honeydew") #define screen color
window.title("Most Frequent Words") #set window title
if f[0] < 960:
y = 500
y_pos = -480
width = 60
spacing = 20
x_pos = -(30+40*(n-1))
else:
width = 100
spacing = 40
y = f[0]/2+20
y_pos = -f[0]/2
x_pos = -(50+70*(n-1))
#turtle.screensize(y,y) #set window size
turtle.setworldcoordinates(-y,-y,y,y)
tortoise = turtle.Turtle() #create turtle
tortoise.hideturtle() #hide turtle stamp
tortoise.penup() #raise turtle pen
tortoise.setposition(x_pos,y_pos) #position turtle
tortoise.pendown() #put turtle pen down
tortoise.speed(5) #set drawing speed
for i in range(n):
if abs(f[i]) < ((f[0]-f[n])/3):
tortoise.color("SeaGreen","ForestGreen") #set turtle color
elif abs(f[i]) >= ((f[0]-f[n])/3) and abs(f[i]) < ((f[0]-f[n])/1.5):
tortoise.color("orange","gold") #set turtle color
else:
tortoise.color("coral3","IndianRed") #set turtle color
tortoise.begin_fill() #begin drawing shapes
tortoise.left(90)
tortoise.forward(f[i]) #draw bar height
tortoise.right(90)
tortoise.forward(1/3*width) #prepare for text
if f[i] >= 0:
tortoise.write(f[i]) #write value
else:
tortoise.penup()
tortoise.right(90)
tortoise.forward(15)
tortoise.write(f[i])
tortoise.forward(-15)
tortoise.left(90)
tortoise.pendown()
tortoise.forward(2/3*width) #bar width
tortoise.right(90)
tortoise.forward(f[i])
tortoise.left(90)
tortoise.penup()
tortoise.right(90)
tortoise.forward(25)
tortoise.left(90)
tortoise.forward(-2/3*width)
tortoise.write(w[i]) #write word
tortoise.forward(2/3*width)
tortoise.left(90)
tortoise.forward(25)
tortoise.right(90)
tortoise.forward(spacing) #spacing
tortoise.pendown()
tortoise.end_fill() #stop drawing shapes
turtle.exitonclick()
dictionary = count_words("New Text Document.txt")
words,values,dictionary = dict_sort(dictionary, reverse = True)
n_freq = word_freq()
graph_word_freq(n_freq,values,words)
from turtle import Screen, Turtle
from collections import defaultdict
PUNCTUATION = "~`!@#$%^&*()_-=+[{]}\\|'\";:,<.>/?"
def remove_punctuation(text):
""" Removes punctuation characters from given text """
text_wo_punctuation = ""
for letter in text:
if letter not in PUNCTUATION:
text_wo_punctuation += letter
return text_wo_punctuation
def count_words(filename):
""" Returns a dictionary of words and word count from "file" """
dictionary = defaultdict(int) # if you won't use Counter, at least use defaultdict()
with open(filename) as file:
text = remove_punctuation(file.read()).lower().split()
for word in text:
dictionary[word] += 1
return dictionary
def dict_sort(d, reverse=False):
"""
Sort given dictionary "d" values (& keys) in ascending (default)
or descending (reverse = True) order
Outputs tuple of: list of keys, list of values
Recommended format for output: k, v = dict_sort(d)
"""
key_list = list(d.keys())
value_list = list(d.values())
for _ in range(len(value_list) - 1):
for i in range(len(value_list) - 1):
if reverse:
if value_list[i] > value_list[i+1]:
value_list[i], value_list[i+1] = value_list[i+1], value_list[i]
key_list[i], key_list[i+1] = key_list[i+1], key_list[i]
else:
if value_list[i] < value_list[i+1]:
value_list[i], value_list[i+1] = value_list[i+1], value_list[i]
key_list[i], key_list[i+1] = key_list[i+1], key_list[i]
return key_list, value_list
def word_freq():
""" Input how many words to plot on graph """
while True:
try:
n_freq = int(input("How many of the most frequent words would you like to display?\n"))
if not 1 <= n_freq <= 10:
print("Please input an integer between 1 and 10:")
continue
except ValueError:
print("Please input an integer between 1 and 10:")
continue
else:
break
return n_freq
def graph_word_freq(n, f, w):
"""
Draw bar chart of most frequent words in text
n: number of words to plot (between 1 and 10)
f: word frequency list
w: word list
"""
window = Screen()
window.bgcolor("honeydew")
window.title("Most Frequent Words")
if f[0] < 960:
width = 60
spacing = 20
y = 500
y_pos = -480
x_pos = - (30 + 40 * (n - 1))
else:
width = 100
spacing = 40
y = f[0] / 2 + 20
y_pos = -f[0] / 2
x_pos = - (50 + 70 * (n - 1))
window.setworldcoordinates(-y, -y, y, y)
tortoise = Turtle(visible=False)
tortoise.speed('fastest') # because I have no patience
tortoise.penup()
tortoise.setposition(x_pos, y_pos)
for i in range(n):
if f[i] < (f[0] - f[n]) / 3:
tortoise.color("SeaGreen", "ForestGreen")
elif (f[0] - f[n]) / 3 <= f[i] < (f[0] - f[n]) / 1.5:
tortoise.color("orange", "gold")
else:
tortoise.color("coral3", "IndianRed")
tortoise.left(90)
tortoise.begin_fill()
tortoise.forward(f[i])
tortoise.right(90)
tortoise.forward(1/2 * width)
tortoise.write(f[i], align='center')
tortoise.forward(1/2 * width)
tortoise.right(90)
tortoise.forward(f[i])
tortoise.end_fill()
tortoise.forward(20)
tortoise.right(90)
tortoise.forward(1/2 * width)
tortoise.write(w[i], align='center')
tortoise.backward(1/2 * width)
tortoise.right(90)
tortoise.forward(20)
tortoise.right(90)
tortoise.forward(spacing)
window.exitonclick()
dictionary = count_words("New Text Document.txt")
words, values = dict_sort(dictionary, reverse=True)
n_freq = word_freq()
graph_word_freq(n_freq, values, words)