ฉันมีรายชื่อของตัวอักษร ฉันอยากจะดึงเครื่องหมายวรรคตอนออกจากรายการและทำให้แต่ละชนิดของเครื่องหมายวรรคตอนเป็นกุญแจอยู่ในพจนานุกรม(ดังนั้นกุญแจสำหรับ".", กุญแจสำหรับ"!", เป็นต้น) งั้นฉันคงชอบนับจำนวนครั้งกันและเครื่องหมายวรรคตอนอักขระเกิดขึ้นในอีกรายการและนั่นนับค่าสำหรับที่สัมพันธ์กันกุญแจสำคัญ. ปัญหาคือทุกค่าอยู่ในพจนานุกรมของฉันเปลี่ยนแปลงแทนที่จะเป็นแค่หนึ่งกุญแจ
การส่งออกควรจะดูเหมือนนี้เพราะว่ามันมี 2"ได้"และ 4"!"ใน'punctuationList'
{'.': [2], ',': [0], '!': [4], '?': [0]}
แต่แทนที่จะเป็นเหมือนว่าเรื่องนี้เพราะคน"!"ดูเหมือน 4 ครั้ง
{'.': [4], ',': [4], '!': [4], '?': [4]}
# Create a list of characters that we will eventually count
charList = [".","!",".","!","!","!","p","p","p","p","p"]
# Create a list of the punctuation we want a count of
punctuationList = [".",",","!","?"]
# Group each type of punctuation and count the number of times it occurs
dic = dict.fromkeys(punctuationList,[0]) # Turn punctuationList into a dictionary with each punctuation type as a key with a value that is
# the count of each time the key appears in newList
print (dic)
# Count each punctuation in the dictionary
for theKey in dic: # iterate through each key (each punctuation type)
counter = 0 # Set the counter at 0
for theChar in charList: # If the key matches the character in the list, then add 1 to the counter
if theKey == theChar:
counter = counter + 1
dic[theKey][0] = counter # Then change the value of that key to the number of times
# that character shows up in the list
print (dic)