【问题标题】:Python: splitting items in a list with multiple spaces?Python:在具有多个空格的列表中拆分项目?
【发布时间】:2016-11-21 12:25:43
【问题描述】:

我有一个包含项目及其属性的文本文件,我想将它们拆分为列表中的单独项目。例如,文本文件中的一行如下所示:

Garlic Bread 100g     400kCal        4g          200mg

我必须创建函数,您可以在其中按名称、卡路里、脂肪等搜索食物。我知道如何将它们拆分为类似 ['Garlic', 'Bread', '100g' '400kCal', '4g', '200mg'] 的列表,但我的目标是让它像 @ 987654323@

我在下面使用了这段代码,但假设我输入了 100g,程序还会输出标题中不包含“100g”的其他食品,而是在其他地方(如钠含量)

itemsearch = input("Enter a food item: ")
itemsearch = [item.strip() for item in itemsearch.lower().split(",")]
with open("nutriton.txt") as TxtFile:
    for thing in TxtFile:
        for item in itemsearch:
            if item in thing:
                print(thing)

对不起,如果我的解释有点混乱。我想我必须对 item[:1] 做点什么,但我需要正确分隔列表项。

【问题讨论】:

    标签: python list python-3.x


    【解决方案1】:
    import re
    line = 'Garlic Bread 100g     400kCal        4g          200mg'
    split_list = re.split(r'\s{2,}', line)
    print(split_list)
    

    出来:

    ['Garlic Bread 100g', '400kCal', '4g', '200mg']
    

    【讨论】:

      猜你喜欢
      • 2018-08-26
      • 2018-11-23
      • 1970-01-01
      • 2020-07-23
      • 2016-02-16
      • 1970-01-01
      • 2014-03-21
      • 2020-06-01
      • 1970-01-01
      相关资源
      最近更新 更多