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

时间:2016-01-07 13:22:14

标签: python regex file python-2.7 python-3.x

我想阅读上面的文件foo.txt并从第一行读取UDE并将其存储在第二行的Unspecified变量中,并将其存储在变量中,依此类推。 我应该使用读取还是读取线?我应该使用正则表达式吗? 我的下面的程序正在阅读整行。如何阅读该行中的具体单词?

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()

2 个答案:

答案 0 :(得分:1)

您可以使用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()

答案 1 :(得分:0)

虽然您可以使用@furas响应或正则表达式,但我建议您使用配置文件来执行此操作,而不是使用普通的txt。所以你的配置文件看起来像:

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

在你的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')