【问题标题】:Generator not working to split string by particular identifier . Python 2生成器无法按特定标识符拆分字符串。蟒蛇2
【发布时间】:2014-12-08 16:40:08
【问题描述】:

到目前为止,我已经找到了一种产生名称、字符串和额外字符串的方法。它适用于第二个,但不适用于第一个?这很奇怪,因为格式非常相似。是因为它是多行吗?我认为if line == '+': pass 会绕过这个问题。

我在 print '\n' 中添加以显示差异

输入:

@first_name
AlongStringOfText
ThatHasNoSpaces
ButIsSeparatedByLineBreaks
+
{+iuhsfIUHSDFUi8849308989829
0990+-]@@@#*$()(@*$*)))***)@@**@#*u
sdfiuhnknwuiewi
+
@second_name
MoreTextThatCouldBeOnOneLine
+
+{~~~(@#UhuisdfiuhIUHDSFIUFHIl)}9823)88hafff
#empty line at end

当前脚本:

def organize(input_file):
    name = None
    body = ''
    extra = ''
    for line in input_file:
        line = line.strip()
        if line.startswith('@'):
            if name: 
                yield name, body, extra
                body = ''
                extra = ''
            name = line
        else:
            body = body + line
            if line == '+':
                pass
    print '\n'
    body,extra = body.split('+',1)

    yield name,body,extra

for line in organize(file_path):
    print line

输出:

('@first_name', 'AlongStringOfTextThatHasNoSpacesButIsSeparatedByLineBreaks+{+iuhsfIUHSDFUi88493089898290990+-]@@@#*$()(@*$*)))***)@@**@#*usdfiuhnknwuiewi+', '')


('@second_name', 'MoreTextThatCouldBeOnOneLine', '+{~~~(@#UhuisdfiuhIUHDSFIUFHIl)}9823)88hafff')

期望的输出:

('@first_name','AlongStringOfTextThatHasNoSpacesButIsSeparatedByLineBreaks','{+iuhsfIUHSDFUi88493089898290990+-]@@@#*$()(@*$*)))***)@@**@#*usdfiuhnknwuiewi')
('@second_name','MoreTextThatCouldBeOnOneLine','+{~~~(@#UhuisdfiuhIUHDSFIUFHIl)}9823)88hafff')

【问题讨论】:

  • 如果把第一个yield改成yield name, body(去掉extra,好像就随心所欲了?

标签: python string split generator yield


【解决方案1】:

实际的问题是,在屈服之前你不是spliting。所以把代码改成这样

    if line.startswith('@'):
        if name: 
            body, extra = body.split('+',1)
            yield name, body, extra
            body = ''
        name = line
    else:
        body = body + line
body, extra = body.split('+',1)
yield name, body, extra

另外,下面的if 条件对程序的输出没有影响

if line == '+':
    pass

所以,我在上面的代码中删除了它。

【讨论】:

  • @draconisthe0ry 谢谢 :-)
  • 我遇到了这个问题。 . .当非名称行和非+行上的第一个字符为“@”时
猜你喜欢
  • 1970-01-01
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多