gpt4 book ai didi

Python:如何将用户输入中的文本与文本文件或mysql数据库中的内容进行比较?

转载 作者:行者123 更新时间:2023-12-01 09:19:28 25 4
gpt4 key购买 nike

如果我在 python 应用程序中添加这两个变量,如何将输入“key”的输入与文本行(整数,例如:12345、67890)进行比较,以在位于 www.example 的文本文件中查找匹配值。 com/key.txt ?

name = raw_input("What is your name ? ")
key = raw_input("What is your key ? ")

我也考虑过将其与数据库内容进行比较,但下面的代码不起作用。

import mysql.connector

email = raw_input("What is your email ? ")
key = raw_input("What is your key ? ")

cnx = mysql.connector.connect(user='root', password="79032", database='license_key')
cursor = cnx.cursor()

query = ("SELECT email_address, license_key FROM validation "
"WHERE license_key LIKE key")

cursor.execute(query, (license_key))

for (email_address, license_key) in cursor:
print("you license key is valid"))

cursor.close()
cnx.close()

最佳答案

您需要读入文本文件(字典就可以),然后检查键/以这种方式分配新值。如果需要,您可以再次将其保存为文本。

示例:如果您有一个包含两列的文本文件(第一列是键,第二列是值),您可以执行以下操作:

example_dict = {}
# Open the file (this takes a path to the file)
with open("key.txt") as f:
# Loop over each line
for line in f:
# Split each line and get the 1st (key) and 2nd (val) values
(key, val) = line.split()
# Cast the key to an integer (not necessary if your key is a string)
example_dict[int(key)] = val

然后,寻找 key :

name = raw_input("What is your name ? ")
key = raw_input("What is your key ? ")

# Here you check if the key is present
if key in example_dict:
# Here you set it to something new, like the name you got, if you wanted to
example_dict[key] = name

关于Python:如何将用户输入中的文本与文本文件或mysql数据库中的内容进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50916364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com