【问题标题】:How to read ONLY 1 word in python?如何在 python 中只读取 1 个单词?
【发布时间】:2021-10-02 22:39:09
【问题描述】:

我创建了一个空文本文件,并在其中保存了一些内容。这是我保存的:

 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”。

【问题讨论】:

  • 和你只读一行一样:你读more超过一行,然后忽略多余的。 (严格来说,readline() 并没有完全丢弃多余的内容——它只是将它放在缓冲区中,以便以后用户要求阅读更多内容时使用——但要点是一样的:你不能要求操作系统读取一个单词或一行,因此您需要一次读取一个字节,直到到达单词分隔符或行分隔符,或者只读取更大的块并仅关注您实际关心的子集)。

标签: python linux raspberry-pi text-files


【解决方案1】:

当您给split() 设置一个限制时,从该限制到末尾的所有项目都会合并。所以如果你这样做了

lines = 'Saish ddd TestUser ForTestUse'
split = lines.split(None, 2)

结果是

['Saish', 'ddd', 'TestUser ForTestUse']

如果你只想要第三个字,请不要限制split()。

second = lines.split()[2]

【讨论】:

  • 但是当我输入:third = lines.split()[4] 它给了我一个错误:third = lines.split()[4] IndexError: list index out of range
  • 只有4个词,所以最高索引是3
【解决方案2】:

你可以直接使用它而无需传递任何None

lines.split()[2]

我理解你的传递 (None, 2) 因为如果索引 2 处没有值,你想得到 None, 检查索引是否在列表中可用的简单方法

Python 2

2 in zip(*enumerate(lines.split()))[0]

Python 3

2 in list(zip(*enumerate(lines.split())))[0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-14
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    相关资源
    最近更新 更多