这个文本处理代码是python的吗?

2024-09-28 23:29:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要取一行文字(单词),在行中点后的第一个空格处将其一分为二;例如:

The quick brown fox jumps over the lazy dog.
                         ^

上面这条线的中点在位置22,这条线在单词“jumps”后面的空格处分开。你知道吗

如果您能看一下下面的代码并告诉我它是否是Pythonic,我将不胜感激。如果没有,请建议正确的方法。非常感谢。(PS:我来自C++背景)

    midLine = len(line) / 2                  # Locate mid-point of line.
    foundSpace = False
    # Traverse the second half of the line and look for a space.
    for ii in range(midLine):
        if line[midLine + ii] == ' ':        # Found a space.
            foundSpace = True
            break
    if (foundSpace == True):
        linePart1 = line[:midLine + ii]      # Start of line to location of space - 1.
        linePart2 = line[midLine + ii + 1:]  # Location of space + 1 to end of line.

Tags: ofthetotrueforiflinespace
3条回答

我不确定Python的方式,但有一些技巧你可以使用:

您可以将行拆分为两半,然后搜索:

the2ndPart = line[len(line) / 2 :]

您不必使用for

firstSpace = the2ndPart.find("")

不需要在if语句中使用(),也可以用于真/假使用is

 if foundSpace is True:

*通过@user7610注释,您可以使用:

if foundSpace:

只是为了好玩,这里有一个soulotion在一行:

myString = "The quick brown fox jumps over the lazy dog."

halfWay = len(myString) / 2

print myString[myString[halfWay:].find(" ") + halfWay :]

输出:

 over the lazy dog.

我能给你的最好的“pythonic”提示是:“pythonic”方法是好的,直到它不可读为止,有时简单更好。你知道吗

我想这更清楚了

midLine = len(line) / 2  
part1 = line[:midLine]
part2 = line[midLine:]
left, right = part2.split(' ', 1)
linePart1 = part1+left
linePart2 = right

Pythonic是在可用的情况下使用内置函数。string.index在这里工作。你知道吗

def half(s):
    idx = s.index(' ', len(s) / 2)
    return s[:idx], s[idx+1:]

如果没有合适的位置断开字符串,则会引发ValueError。如果不是你想要的,你可能不得不调整代码。你知道吗

相关问题 更多 >