繁体   English   中英

用Python正确的方式解析字符串

[英]Parsing string with Python correct way

我在解析正确的方法时遇到了一些问题。 我想将完整的字符串分成两个单独的字符串。 然后从第一个字符串中删除“ =”符号,从第二个字符串中删除“,”符号。 从我的输出中,我可以得出结论:我做错了什么,但是我似乎并没有找到问题所在。 我希望第一部分转换为整数,并且已经使用map(int,split())进行了尝试。

如果有人给我小费,我将不胜感激。

这是我的输出:

('5=20=22=10=2=0=0=1=0=1', 'Vincent Appel,Johannes Mondriaan')

这是我的程序:

mystring = "5=20=22=10=2=0=0=1=0=1;Vincent Appel,Johannes Mondriaan"

def split_string(mystring):
    strings = mystring.split(";")
    x = strings[0]
    y = strings[-1]
    print(x,y)

def split_scores(x):
    scores = x.split("=")
    score = scores[0]
    names = scores[-1]
    stnames(names)
    print score

def stnames(y):
    studentname = y.split(",")
    name = studentname[1]
    print name

split_string(mystring)

split_string(mystring)运行第一个函数,生成包含2个字符串的元组。 但是没有任何功能可以运行旨在执行进一步拆分的其他功能。

尝试:

x, y = split_string(mystring)
x1 = split_scores(x)
y1 = stnames(y)
(x1, y1)

糟糕,您的函数会打印结果,而不返回结果。 因此,您还需要:

def split_string(mystring):
    # split mystring on ";"
    strings = mystring.split(";")
    return strings[0],strings[1]

def split_string(mystring):
    # this version raises an error if mystring does not have 2 parts
    x, y = mystring.split(";")
    return x,y

def split_scores(x):
    # return a list with all the scores
    return x.split("=")

def stnames(y):
    # return a list with all names
    return y.split(",")

def lastname(y):
    # return the last name (, delimited string)
    return y.split(",")[-1]

如果要在功能之间拆分任务,最好让它们返回结果而不是打印结果。 这样,它们可以以各种组合使用。 在函数中print仅用于调试目的。

或紧凑的脚本版本:

x, y = mystring.split(';')
x = x.split('=')
y = y.split(',')[-1]
print y, x

如果您希望分数为数字,请添加:

x = [int(x) for x in x]

来处理。

尝试这个:

def split_string(mystring):
    strings = mystring.split(";")
    x = int(strings[0].replace("=",""))
    y = strings[-1].replace(","," ")
    print x,y

我的两分钱。

如果我了解您要实现的目标,则此代码可以帮助您:

mystring = "5=20=22=10=2=0=0=1=0=1;Vincent Appel,Johannes Mondriaan"

def assignGradesToStudents(grades_and_indexes, students):
    list_length = len(grades_and_indexes)
    if list_length%2 == 0:
        grades = grades_and_indexes[:list_length/2]
        indexes = grades_and_indexes[list_length/2:]
        return zip([students[int(x)] for x in indexes], grades)

grades_and_indexes, students = mystring.split(';')
students = students.split(',')
grades_and_indexes = grades_and_indexes.split('=')

results = assignGradesToStudents(grades_and_indexes, students)
for result in results:
    print "[*] {} got a {}".format(result[0], result[1])

输出:

[*] Vincent Appel got a 5
[*] Vincent Appel got a 20
[*] Johannes Mondriaan got a 22
[*] Vincent Appel got a 10
[*] Johannes Mondriaan got a 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM