我学习Python时间不长,在学习了基础知识之后,我完成了一些我在网上找到的任务。
对于这个,我将使用字符列表(在本例中为字母表)来计算句子中这些字符的数量。
我已经到了这样的地步:它正在计算一些东西,但在字符 c 上被剪掉,当里面只有 1 个 c 时,它给我一个值为 30 的值,然后返回:
File "/home/pi/main.py", line 17, in <module>
if statementLower[l] == alphabet[m]:
IndexError: string index out of range
附代码
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
statement = "This is my task I want to complete. But I am stuck!!!!!!"
statementLower = statement.lower()
m = 0
l=0
count = 0
print(statementLower)
for i in alphabet:
frequency = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
#print("i for alphabet")
#print("-" + i + "-")
for k in statementLower:
#print("k statement Lower")
#print(k)
if statementLower[l] == alphabet[m]:
#print(count)
count = count+1
frequency[m] = count
l+l+1
continue
else:
#print("else continue loop")
l=l+1
continue
if frequency[m] != 0:
#print("frequency loop")
print(str(alphabet[m]+ ":" + str(frequency[m])))
m=m+1
count = 0
l=0
continue
任何人都可以为我做错的事情提供任何帮助吗?我可以看到我不断陷入该 count if 语句,但即使我增加该值,它也不会增加到字符串的下一个索引。
我目前唯一的回报是 答:44 早:20 时间:30 那么字符串索引超出范围
我注意到您的代码中有两个错误:
l+l+1
语句;可能是拼写错误,您的意思是l=l+1
。纠正这些错误将使您的代码按预期工作。下面是您的原始源文件(顶部没有初始化程序);我留下了评论,记录了这些错误是什么(并添加了一些关于如何使代码更加“Pythonic”的提示)。
for i in alphabet:
frequency = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for k in statementLower:
if statementLower[l] == alphabet[m]:
count = count + 1 # Can be simplified to count += 1
frequency[m] = count # You don't have to have the "count" variable at all; instead, you can simply use frequency[m]. That'll save you the hassle of keeping track of an extra variable.
# If you want to stop using the "count" variable, simply replace the above two lines with "frequency[m] += 1". You can then delete all lines referencing "count".
l+l+1 # This statement will do nothing; you probably meant the first "+" to be a "=".
continue
else:
# These assignments can be moved outside the else-if; and, as this is the only statement in the else-if,
# the else can be removed completely.
l=l+1
continue
if frequency[m] != 0:
print(str(alphabet[m]+ ":" + str(frequency[m])))
# You are only resetting your counter variables if the current frequency value is not 0.
# The reason why your code didn't execute correctly after "c" is because there are no
# "d" characters in the string; so you're not updating m, count, and l after you encounter such a character.
m=m+1
count = 0
l=0
continue
此外,您的脚本可以简化为:
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
statement = "This is my task I want to complete. But I am stuck!!!!!!"
statementLower = statement.lower()
m = 0
l=0
count = 0
print(statementLower)
frequency = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# For each letter index of the array "alphabet"
for i in range(len(alphabet)):
# For each character of the string "statementLower"
for k in statementLower:
# If the character is equal to the character under the alphabet index i...
if k == alphabet[i]:
# ...add 1 to the frequency under that index.
frequency[i] += 1
# Print out the frequencies
for i in range(len(alphabet)):
if frequency[i] != 0:
print(str(alphabet[i]+ ": " + str(frequency[i])))
# bonus: f-strings! they're cool, fancy, and are more pythonic! :3
# print(f"{alphabet[i]}: {frequency[i]}")
祝你的 Python 事业好运!
正如已经说过的,collections.Counter 是理想的选择。但是,如果您想在不导入任何内容的情况下执行此操作,您可以考虑使用字典(这本质上就是 Counter 的实现方式)。字典将键入在 statement 字符串中找到的 a-z 范围内的任何字母。
statement = 'This is my task I want to complete. But I am stuck!!!!!!'
result = {}
for letter in statement.lower():
if letter.isalpha():
result[letter] = result.get(letter, 0) + 1
for key, value in sorted(result.items()):
print(f'{key}={value}')
输出:
a=3
b=1
c=2
e=2
h=1
i=4
k=2
l=1
m=3
n=1
o=2
p=1
s=4
t=7
u=2
w=1
y=1
我想出了这个,类似于第一个答案:
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
statement = "This is my task I want to complete. But I am stuck!!!!!!"
statementLower = statement.lower()
print(statementLower)
setz = [i for i in statementLower if i in alphabet ] #list of char in statementLower if they are in alphabet
print(setz)
#freqs = [(item, setz.count(item)) for item in set(setz)] #freq as list, uses .count() method on set() of setz
freqs = dict([(item, setz.count(item)) for item in set(setz)]) # freqs as dictionary, see above
print(freqs)
输出:
this is my task i want to complete. but i am stuck!!!!!!
['t', 'h', 'i', 's', 'i', 's', 'm', 'y', 't', 'a', 's', 'k', 'i', 'w', 'a', 'n', 't', 't', 'o', 'c', 'o', 'm', 'p', 'l', 'e', 't', 'e', 'b', 'u', 't', 'i', 'a', 'm', 's', 't', 'u', 'c', 'k']
{'w': 1, 'm': 3, 'b': 1, 'n': 1, 'c': 2, 'a': 3, 'k': 2, 'h': 1, 'l': 1, 'u': 2, 'o': 2, 'e': 2, 'y': 1, 's': 4, 'i': 4, 'p': 1, 't': 7}
我的缺点是 Python 3.6 字典保留了
inserting order
,而我的字典不遵循字母表,请参阅:Python 3.6+ 中的字典是有序的吗?
第一个选项:使用
collections.Counter
。正如 Steven Rumbalski 所建议的:
frequency = collections.Counter(filter(str.isalpha, statement.lower()))
如果你想要更多的工作,那么有
str.count()
方法。建议:让我们将 frequency
改为 dict
而不是 list
frequency = {}
for a in alphabet:
frequency[a] = statementLower.count(a)
如果您还想要更多工作,好的:
frequency = {a:0 for a in alphabet} #or use a defaultdict instead
for a in alphabet:
for ch in statementLower:
if a == ch:
frequency[a] += 1