用逗号或 \n 分割列表

时间:2021-05-24 16:26:13

标签: python

我对 python 还很陌生,所以请耐心等待,但我有一个文本文件(用 Path 打开),里面有一个字典,我试图将它拆分成单独的行(不更改文件。 ) 有些行有多个键和索引,以逗号分隔,有些行只有一个。 我试过 re.split('\n |, ', lines) 但我得到了错误:

'_io.TextIOWrapper' object has no attribute 'split'

文件例如: cake: dessert, kale: vegetable \n carrots: vegetable \n pears: fruit \n peaches: fruit \n peaches: fruit

这是我现在拥有的

def get_most_popular_foods(file_path):
""" Read in survey and determine the most common food of each type.

Parameters
----------
file_path : str
    Path to text file containing favorite food survey responses.     

Returns
-------
Dict[str, str]
    Dictionary with the key being food type and value being food.
"""

from pathlib import Path
import re
path_to_file = Path(file_path)
with open(path_to_file, mode="r") as f:
    lines = f.readlines()
    lines2 = re.split('\n |, ', lines)
    print(lines2)

运行此程序时出现错误“TypeError: expected string or bytes-like object” 我的最终目标是把它放在我可以找到每种食物中最受欢迎的地方,所以这个例子的结果是

{'dessert': 'cake', 'vegetable': 'carrots', 'fruit': 'peaches'}

但我可以再次访问其余的代码,现在我只需要整理列表。我认为最好将每个 index:key 对放在单独的行上,但我愿意接受建议。

1 个答案:

答案 0 :(得分:1)

Traceback (most recent call last): File "[...]/ranks_2.py", line 29, in <module> hof = HallOfFame() TypeError: __init__() missing 2 required positional arguments: 'owner' and 'hall_of_fame' 方法会将您的字符串拆分为子字符串列表。

split
相关问题