Python如何从文本文件中仅读取单个单词?split分割结果异常问题求解
错误原因
str.split(sep, maxsplit)的第二个参数maxsplit表示最大分割次数,你设置maxsplit=2时仅会执行2次分割,最终得到3个元素的列表,第三个元素为剩余所有未分割的内容,因此取索引[2]会返回TestUser ForTestUse两个单词。
修复方案
无需指定maxsplit参数,直接调用无参数的split()方法即可,该方法默认按任意空白字符分割,会自动忽略文件开头的前置空格,将所有单词拆分为列表,再按索引取对应单词即可,TestUser对应的索引为2,修改后的代码段如下:
elif ans == '2': print('Switching to accounts...') time.sleep(0.5) with open("User_Data.txt") as f: lines = f.read() words = lines.split() second = words[2] print(second)
可选优化
可以提前一次性读取所有单词存为列表,无需每次切换用户都重复读取文件,代码更简洁高效,完整优化版代码如下:
import time print("Loading Data...") time.sleep(2) # 提前一次性读取所有单词 with open("User_Data.txt") as f: words = f.read().split() first = words[0] print(first) print("Type user number 1 - 4 for using different user.") ans = input('Is the name above correct?(y/1 - 4) ') if ans == 'y': print("Ok! You will be called", first) elif ans == '1': print("You are already registered to", first) elif ans == '2': print('Switching to accounts...') time.sleep(0.5) second = words[2] print(second) # 后续3、4号用户直接取 words[3]、words[4] 即可 #Fix the passord issue! Very important as this is SECURITY!!!
内容的提问来源于stack exchange,提问作者RockZombie
相关产品推荐
相关产品推荐

