ChatGPT写python代码例子,真的好方便。
输入:
写python代码方法 从a.txt文件读出每一行,要支持中文,然后对比传入的字符串,相等返回真,否则返回假。
回答:
您可以使用以下代码读取a.txt文件并对比传入的字符串:
def compare_string(file_path, target_string): with open(file_path, 'r', encoding='utf-8') as file: for line in file: if line.strip() == target_string: return True return False
在这个函数中,我们使用了with语句来自动关闭文件句柄。使用open函数打开文件时,指定编码为utf-8以支持中文。
for line in file 语句遍历文件中的每一行,使用strip()方法删除行尾的空白字符(包括换行符),并将其与目标字符串进行比较。如果匹配成功,返回True,否则继续遍历。如果遍历完整个文件后没有找到匹配项,则返回False。
您可以使用以下代码来测试此函数:
file_path = 'a.txt' target_string = '你好' result = compare_string(file_path, target_string) print(result) # 输出 True 或 False
切图如下:
继续输入:
如果a.txt 文件一行中有中英文对应,用逗号分隔,都需要和转入的字符串对比。
回答:
如果您的a.txt文件中的每行包含多个中英文混合的字符串,以逗号分隔,并且您需要将每个字符串与传入的目标字符串进行比较,您可以使用以下代码:
def compare_string(file_path, target_string):
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
strings = line.strip().split(',')
for s in strings:
if s.strip() == target_string:
return True
return False
在这个函数中,我们首先使用split()方法将行按逗号分隔成多个字符串,然后使用for循环遍历这些字符串。对于每个字符串,我们使用strip()方法删除前后的空白字符,并将其与目标字符串进行比较。如果找到匹配项,返回True,否则继续遍历。如果遍历完整个文件后没有找到匹配项,则返回False。
您可以使用以下代码来测试此函数:
file_path = 'a.txt'
target_string = 'hello'
result = compare_string(file_path, target_string)
print(result) # 输出 True 或 False
假设a.txt文件内容如下:
你好,hello,世界
Python, is, a, programming, language
对于目标字符串hello,函数将返回True,因为它匹配了第一行中的hello字符串。对于目标字符串is,函数将返回True,因为它匹配了第二行中的is字符串。对于目标字符串world,函数将返回False,因为它没有出现在文件中。
直接复制测试下,果然可用,真强大。