- 在 Python 代码中使用正则表达式时,出现 “TypeError: ‘int’ object is not callable” 错误。
- 出现此错误的原因是,代码中将一个整型数字作为正则表达式的匹配对象,而正则表达式应该作用于字符串或文本数据。
- 出现此错误的原因是,代码中将一个整型数字作为正则表达式的匹配对象,而正则表达式应该作用于字符串或文本数据。
- 解决方案:
- 将整型数字转换为字符串格式,然后使用正则表达式进行匹配。
- 以下是修改后的代码:
import random
import re
# Contains the question and it's correct answer
my_dict = {
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
"A form of Protectionism that imposes a tax on imports" : "tariff",
"....is quantity of a good or service that consumers are willing and able to buy at a given price in a given time period" : "Demand",
"....is the quantity of a good or service that a producer is willing and able to supply onto the market at a given price in a given time period" : "Supply",
"By using ..... businesses can bring down their average costs by producing on a larger scale" : "Economies of scale",
"The cost of the next best alternative" : "Opportunity Cost",
".... is the transfer of assets from the public (government) sector to the private sector." : "Privatisation"
}
# welcome message
print("Economics Revision App")
print("=======================")
# the quiz will end when this variable becomes 'False'
playing = True
# While the game is running
while playing == True:
# set the score to 0
score = 0
# gets the number of questions the player wants to answer
num = input("\nHow many questions would you like: ")
match = re.match("r\d[0-9]{2}$", str(num))
if match:
print ('foo')
# loop the correct number of times
for i in range(num):
# the question is one of the dictionary keys, picked at random
question = (random.choice( list(my_dict.keys())))
# the answer is the string mapped to the question key
answer = my_dict[question]
# print the question, along with the question number
print("\nQuestion " + str(i+1) )
print(question + "?")
# get the user's answer attempt
guess = input("> ")
# if their guess is the same as the answer
if guess.lower() == answer.lower():
# add 1 to the score and print a message
print("Correct!")
score += 1
else:
print("Incorrect guess again!")
# after the quiz, print their final score
print("\nYour final score was " + str(score))
# store the user's input...
again = input("Enter any key to play again, or 'q' to quit.")
#... and quit if they types 'q'
if again.lower() == 'q':
playing = False
-
在代码中,将 num = int(input("\nHow many questions would you like: “)) 改为了 num = input(”\nHow many questions would you like: "), 这将接受输入的字符串,而不是整型数字。
-
在使用正则表达式进行匹配之前,使用了 match = re.match(“r\d[0-9]{2}$”, str(num)) 将字符串 num 转换为字符串格式。
-
这样,就解决了 “TypeError: ‘int’ object is not callable” 错误。