【问题标题】:Wrong output from code using isspace() test over index values使用 isspace() 测试索引值的代码输出错误
【发布时间】:2020-02-18 08:53:56
【问题描述】:

由于某种原因,此代码无法正常工作。我试图只替换周围没有空格的破折号。但是,当没有空格时,破折号仍然会被替换。

    ls = []
    for idx, letter in enumerate(line):
        if letter == '-':
            ls.append(idx)
    for m in ls:
        if line[m-1].isspace() == True and line[m+1].isspace() == True:
            line = line[m].replace('-', ' @-@ ')

例如:

If thieves came to you, if robbers by night -- oh, what disaster awaits you -- wouldn't they only steal until they had enough? If grape pickers came to you, wouldn't they leave some gleaning grapes?
How Esau will be ransacked! How his hidden treasures are sought out example-case!

给予:

If thieves came to you , if robbers by night  @-@  @-@  oh , what disaster awaits you  @-@  @-@  wouldn ' t they only steal until they had enough ? If grape pickers came to you , wouldn ' t they leave some gleaning grapes ?
How Esau will be ransacked ! How his hidden treasures are sought out example @-@ case !

注意:这里还有其他数据标记化。

期望的输出是:

If thieves came to you , if robbers by night -- oh , what disaster awaits you -- wouldn ' t they only steal until they had enough ? If grape pickers came to you , wouldn ' t they leave some gleaning grapes ?
How Esau will be ransacked ! How his hidden treasures are sought out example @-@ case !

感谢您的帮助!

【问题讨论】:

    标签: python parsing indexing isspace


    【解决方案1】:

    您在访问该行时会对其进行变异,因此如果不手动修复它们,您的索引将是错误的。

    这确实是您想要使用正则表达式的情况:

    import re
    
    line = "How his hidden treasures -- oh, what was the line again -- are sought out example-case!"
    fixed_line = re.sub(r"(?<=[^\s])-(?=[^\s])", " @-@ ", line)
    print(fixed_line)
    

    输出

    How his hidden treasures -- oh, what was the line again -- are sought out example @-@ case!
    

    【讨论】:

    • 实际上,我的代码可以正常工作。我最后出现了一个非常愚蠢的错误。但是,这要整洁得多。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-10-23
    • 2022-01-09
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多