简体   繁体   English

从python文件中读取特定字符串?

[英]read a specific string from a file in python?

I want to read the above file foo.txt and read only UDE from the first line and store it in a variable then Unspecified from the second line and store it in a variable and so on. 我想读取上面的文件foo.txt,仅从第一行读取UDE并将其存储在变量中,然后从第二行将其未指定并存储在变量中,依此类推。 should I use read or readlines ? 我应该使用阅读还是阅读行? should I use regex for this ?? 我应该为此使用正则表达式吗? My below program is reading the entire line. 我下面的程序正在阅读整行。 how to read the specific word in the line ? 如何读取行中的特定单词?

fo = open("foo.txt", "r+")
line = fo.readline()
left, right = line.split(':')
result = right.strip()
File_Info_Domain = result
print File_Info_Domain
line = fo.readline()
left, right = line.split(':')
result = right.strip()
File_Info_Intention = result
print File_Info_Intention
line = fo.readline()
left, right = line.split(':')
result = right.strip()
File_Info_NLU_Result = result
print File_Info_NLU_Result
fo.close()

You can use readline() (without s in name) to read line on-by-one, and then you can use split(':') to get value from line. 您可以使用readline() (名称中没有s )来一对一读取行,然后可以使用split(':')从行中获取值。

fo = open("foo.txt", "r+")

# read first line
line = fo.readline()

# split line only on first ':'
elements = line.split(':', 1) 

if len(elements) < 2:
    print("there is no ':' or there is no value after ':' ")
else:
    # remove spaces and "\n"
    result = elements[1].strip()
    print(result)

#
# time for second line
#

# read second line
line = fo.readline()

# split line only on first ':'
elements = line.split(':', 1)

if len(elements) < 2:
    print("there is no ':' or there is no value after ':' ")
else:
    # remove spaces and "\n"
    result = elements[1].strip()
    print(result)

# close
fo.close()

While you can use @furas response or regex, I would recommend you to use a config file to do this, instead of a plain txt. 虽然您可以使用@furas响应或正则表达式,但我建议您使用配置文件来执行此操作,而不要使用纯文本文件。 So your config file would look like: 因此,您的配置文件如下所示:

[settings]
Domain=UDE
Intention=Unspecified
nlu_slot_details={"Location": {"literal": "18 Slash 6/2015"}, "Search-phrase": {"literal": "18 slash 6/2015"}

And in your python code: 在您的python代码中:

import configparser

config = configparser.RawConfigParser()
config.read("foo.cfg")

domain = config.get('settings', 'Domain')
intention = config.get('settings', 'Intention')
nlu_slot_details = config.get('settings', 'nlu_slot_details')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM