我有一个包含多个记录的字符串。每个记录都有一个由逗号分隔的单词列表。我想将每条记录转换为一组,其中一条记录中的单词就是该组中的值。您能否建议如何将其转换为集合?
例如下面是文件中的两条记录。
citrus fruit,semi-finished bread,margarine,ready soups
tropical fruit,yogurt,coffee
我想将它们转换为:
{'citrus fruit','semi-finished bread','margarine','ready soups'}
{'tropical fruit','yogurt','coffee'}
答案 0 :(得分:0)
使用csv模块。
import csv
def readsets(filename):
with open(filename) as f:
for row in csv.reader(f):
yield set(row)
答案 1 :(得分:0)
我不认为您想要set
,因为在您的示例中,您按期望的结果按顺序列出了所有内容。 set
是无序的,并且不能包含重复项。还不清楚您的记录如何分隔。
下面是一个使用list
维护顺序的示例:
>>> first_record = "citrus fruit,semi-finished bread,margarine,ready soups"
>>> second_record = "tropical fruit,yogurt,coffee"
>>> def tokenize(s, delim=","):
... return s.split(delim)
...
>>> first_result = tokenize(first_record)
>>> first_result
['citrus fruit', 'semi-finished bread', 'margarine', 'ready soups']
>>> second_result = tokenize(second_record)
>>> second_result
['tropical fruit', 'yogurt', 'coffee']
,如果您真的想要set
,只需将其包装在对set
构造函数的调用中即可:
>>> first_result_set = set(first_result)
>>> second_result_set = set(second_result)
>>> first_result_set
{'margarine', 'ready soups', 'semi-finished bread', 'citrus fruit'}
>>> second_result_set
{'coffee', 'yogurt', 'tropical fruit'}
编辑:您可以一次完成所有操作,因为我们知道记录由换行符分隔:
>>> records = "citrus fruit,semi-finished bread,margarine,ready soups\ntropical fruit,yogurt,coffee"
>>> def setitize_records(records, record_delim="\n", item_delim=","):
... record_list = records.split(record_delim)
... record_sets = [set(record.split(",")) for record in record_list]
... return record_sets
...
>>> result = setitize_records(records)
>>> result
[{'margarine', 'ready soups', 'semi-finished bread', 'citrus fruit'}, {'coffee', 'yogurt', 'tropical fruit'}]
答案 2 :(得分:0)
这应该为您工作。检查出来。
type