[英]spliting string from a line and appending in a list in python 3
I have a file which contains with following format in each line I want to write a function which gets the keyword "Main value" and searches for it and gives output. 我有一个文件,其中每一行都包含以下格式,我想编写一个函数,该函数获取关键字“ Main value”并进行搜索并给出输出。
File format: 文件格式:
Main value:value_name,value (1):value_name1,value (2):value_name2 and so on...
Output required: 需要的输出:
Feature name: Main value
Technical name: value_name
Possible values: value_name1
value_name2
value_name3 and so on...
Possible variables: value (1)
value (2)
value (3) and so on...
Code till now: 到目前为止的代码:
def get_feature_infos(file_path, feature_name):
technical_name = []
possible_variables = []
possible_names = []
with open(file_path, "r") as commands_library:
for line in commands_library:
if feature_name in line:
technical_name.append((line.split(",")[0]).split(":")[1])
possible_variables.append(line.split(",")[1].split(":")[0])
possible_names.append(line.split(",")[1].split(":")[1])
print (" Technical name: ", technical_name[0])
print (" Possible values: ", possible_variables[0])
print (" Possible variables: ", possible_names[0])
But this prints only the first possible values but I want all the possible values 但这只打印第一个可能的值,但我要所有可能的值
What I believe you are looking for is a way to print a list of values in a list regardless of how the list is named. 我相信您正在寻找的是一种在列表中打印值列表的方法,而不管列表的命名方式如何。 What you can do is to create a text list.
您可以做的是创建一个文本列表。 For example:
例如:
print (" Technical name: ", ', '.join(technical_name))
You may also want to transpose the output by creating tuples before you print: 您可能还想通过在打印前创建元组来转置输出:
tups = zip(*(technical_name, possible_variables, possible_names))
for tup in tups:
print('{}\t{}\t{}'.format(tup))
Try this. 尝试这个。 It worked for me:
它为我工作:
def get_feature_infos(file_path, feature_name):
technical_name = []
possible_variables = []
possible_names = []
data = []
with open(file_path, "r") as commands_library:
for line in commands_library:
if feature_name in line:
technical_name.append((line.split(",")[0]).split(":")[1])
data = (line.split(","))
data.pop(0)
for shortData in data:
possible_variables.append(shortData.split(":")[0])
possible_names.append(shortData.split(":")[1])
print (" Technical name: ", technical_name[0])
print (" Possible variables: ", possible_variables)
print (" Possible names: ", possible_names)
Let me introduce the second argument of str.split
- maxsplit
to you. 让我介绍的第二个参数
str.split
- maxsplit
给你。
With maxsplit
, you can split "Main value" and the rest: 使用
maxsplit
,您可以拆分“ Main value”和其余的:
feature_name, rest = line.split(':', 1)
then the value_name and the rest: 然后是value_name和其余的:
technical_name, rest = rest.split(',', 1)
then possible_variables and possible_names 然后可能变量和可能名称
possible_variables = [x.split(':')[0] for x in rest.split(',')]
possible_names = [x.split(':')[1] for x in rest.split(',')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.