【问题标题】:read a specific string from a file in python?从python中的文件中读取特定字符串?
【发布时间】:2016-04-11 21:46:06
【问题描述】:

我想读取上面的文件 foo.txt 并从第一行只读取 UDE 并将其存储在一个变量中,然后从第二行未指定并将其存储在一个变量中,依此类推。 我应该使用 read 还是 readlines ?我应该为此使用正则表达式吗? 我下面的程序正在阅读整行。如何阅读该行中的特定单词?

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

【问题讨论】:

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


    【解决方案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()
    

    【讨论】:

    • 我更新了我的代码,但我得到的错误是: Traceback (last recent call last): File ".\file.py", line 46, in left, right = line. split(':') ValueError: 要解压的值太多
    • 那是因为第三行的值太多,在每个:进行拆分
    • 因为你有不止一个: 在行中并且拆分创建了两个以上的元素 - 使用elements = line.split(':') 然后elements[1] 来获取元素。
    • 你能在代码中更新它吗?这令人困惑。是否正确 - # 读取第三行 line = fo.readline() elements = line.split(':') elements[1] = elements result3 = right.strip() File_Info_NLU_Result = result3 print File_Info_NLU_Result
    • 顺便说一句:您要求第一行和第二行 - 第三行需要修改 - split 需要另一个参数才能仅在第一个“:”上滑动。
    【解决方案2】:

    虽然您可以使用@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')
    

    【讨论】:

    • 我同意你的看法 :) 我打算建议 jsonyaml
    • 我收到一个错误:ImportError: No module named configparser
    • @akshay 如果你使用 Python 2.7 试试ConfigParser
    • 你需要安装包。你可以用 pip 做到这一点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 2019-06-21
    相关资源
    最近更新 更多