python - 如何在 python 中只读取 1 个单词?
问题描述
我创建了一个空文本文件,并在其中保存了一些内容。这是我保存的:
Saish ddd TestUser ForTestUse
在这些词之前有一个空格。无论如何,我想知道如何使用 python 在文本文件中只读取 1 个 WORD。这是我使用的代码:
#Uncommenting the line below the line does literally nothing.
import time
#import mmap, re
print("Loading Data...")
time.sleep(2)
with open("User_Data.txt") as f:
lines = f.read() ##Assume the sample file has 3 lines
first = lines.split(None, 1)[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)
with open("User_Data.txt") as f:
lines = f.read() ##Assume the sample file has 3 lines
second = lines.split(None, 2)[2]
print(second)
#Fix the passord issue! Very important as this is SECURITY!!!
当我运行代码时,我的输出是:
Loading Data...
Saish
Type user number 1 - 4 for using different user.
Is the name above correct?(y/1 - 4) 2
Switching to accounts...
TestUser ForTestUse
如您所见,它同时显示“TestUser”和“ForTestUse”,而我只希望它显示“TestUser”。
解决方案
当你给 一个限制时split()
,从那个限制到结束的所有项目都被组合起来。所以如果你这样做
lines = 'Saish ddd TestUser ForTestUse'
split = lines.split(None, 2)
结果是
['Saish', 'ddd', 'TestUser ForTestUse']
如果您只想要第三个单词,请不要限制split()
.
second = lines.split()[2]
推荐阅读
- c - 我应该将参数存储类说明符放在函数定义中还是同时放在声明和定义中?
- python - TypeError: done() takes 1 positional argument but 2 were given
- nginx - 在位置重写,为反向代理的 proxy_pass
- azure - Azure ElasticSearch 定价和维护
- google-apps-script - 将云端硬盘文件夹中的图片添加到表单问题
- vba - 使用两个值验证多个文本框以汇总报告
- database - 将 .csv 文件上传到元数据库
- css - 块的曲线右侧形状
- laravel - 带有 Eloquent 更新的 Laravel 5.7 监听器
- python - 如何编写 Django 'if then else' 语句逻辑