【问题标题】:Python String to list processingPython 字符串到列表处理
【发布时间】:2012-01-02 17:43:27
【问题描述】:

我觉得我最近获得的关于字符串处理的知识仍然不够。请帮我解决以下问题陈述: (请注意:这是我要求的更简单的版本)

所以.. 我有一个文件(myoption),内容如下:

day=monday,tuesday,wednesday
month=jan,feb,march,april
holiday=thanksgiving,chirstmas

我的 python 脚本应该能够读取文件并处理读取的信息,这样最后我就有了三个列表变量,如下所示:

day --> ['monday','tuesday','wednesday']
month --> ['jan','feb','march','april']
holiday --> ['thanksgiving','christmas']

请注意: 根据我的要求,myoption 文件中内容的格式应该很简单。 因此,您可以在不更改内容的情况下随意修改“myoption”文件的格式 - 这是为了给您一些灵活性。

谢谢:)

【问题讨论】:

  • 为什么不坚持经典格式而只使用 ConfigParser?
  • @Raymond 感谢您提供有关 configparser 的信息,我会调查一下。
  • @AnimeshSharma 我喜欢confiparser的答案,无论如何我建议你如何使用你的格式

标签: python string file list


【解决方案1】:

您可能对ConfigParser module.感兴趣

【讨论】:

    【解决方案2】:

    如果您希望您的应用程序遵守标准,您可以用 YAML 或 XML 重写您的文件。 无论如何,如果你想保持简单的格式,这应该是:

    给定文件数据

    day=monday,tuesday,wednesday
    month=jan,feb,march,april
    holiday=thanksgiving,chirstmas
    

    我提出这个 python 脚本

    f = open("data")
    for line in f:
      content = line.split("=")
      #vars to set the variable name as the string found and 
      #[:-1] to remove the new line character
      vars()[content[0]] = content[1][:-1].split(",")
    print day
    print month
    print holiday
    f.close()
    

    输出是

    python main.py 
    ['monday', 'tuesday', 'wednesday']
    ['jan', 'feb', 'march', 'april']
    ['thanksgiving', 'chirstmas']
    

    【讨论】:

      【解决方案3】:

      这是一个简单的答案:

      s = 'day=monday,tuesday,wednesday'
      mylist = {}
      key, value = s.split('=')
      mylist[key] = value.split(',')
      
      print mylist['day'][0]
      
      Output: monday
      

      【讨论】:

      • 最好习惯不使用list作为变量名,它隐藏了内置并可能导致难以调试的错误。
      • 谢谢,我在发布答案后对此感到疑惑,重新编辑。
      • 感谢 Alvin 抽出宝贵时间。现在我知道我的问题有两种解决方案:)
      • 我主张将ConfigParser 作为首选(即:尽可能不要重新发明轮子:)。
      【解决方案4】:

      如果您使用the standard ConfigParser module,您的数据需要在INI file format 中,因此看起来像这样:

      [options]
      day = monday,tuesday,wednesday
      month = jan,feb,march,april
      holiday = thanksgiving,christmas
      

      然后你可以按如下方式读取文件:

      import ConfigParser
      
      parser = ConfigParser.ConfigParser()
      parser.read('myoption.ini')
      day = parser.get('options','day').split(',')
      month = parser.get('options','month').split(',')
      holiday = parser.get('options','holiday').split(',')
      

      【讨论】:

      • 有没有使用configparser追加新数据到INI文件中?使用 .set 我可以添加数据,但它会覆盖旧文件。因此,如果我将新数据附加到旧 INI 文件 - 到目前为止,我必须添加新数据和旧数据,这需要额外的资源。
      猜你喜欢
      • 1970-01-01
      • 2023-02-26
      • 2012-07-27
      • 2016-09-19
      • 2012-08-07
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      相关资源
      最近更新 更多