0

文字列の最初のトレイル空白のインデックスを見つける関数を書いていますが、その方法がわかりません。誰か教えてもらえますか?

たとえば、「私はここにいます。」 文の後に 3 つのスペースがあります。関数は私に「10」を与えるでしょう。

入力は、文(文字列のリスト)に分割されたテキストpythonファイルを対象としています

これは私が試したことです

alplist = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] 
space = [' ', ',', '.', '(', ')', ':', ':']

def TRAIL_WHITESPACE(python_filename): 
    whitespace = [] 
    LINE_NUMBER = 1 
    index = 0 
    for item in lines: 
        for index in range(len(item)): 
            if len(item) > 0: 
                if item[index] + item[index + 1] in alplist + space: 
                    index = index 
                    if item[index:] in " ": 
                        whitespace.append({'ERROR_TYPE':'TRAIL_WHITESPACE', 'LINE_NUMBER': str(LINE_NUMBER),'COLUMN': str(index),'INFO': '','SOURCE_LINE': str(lines[ len(item) - 1])}) 
                        LINE_NUMBER += 1 
                    else: 
                        LINE_NUMBER += 1 
                else: 
                    LINE_NUMBER += 1 
            else: 
                LINE_NUMBER += 1 
    return whitespace

ありがとうございました

4

3 に答える 3

2

str.rstrip()これは、次のメソッドを使用して簡単に実行できます。

#! /usr/bin/env python

#Find index of any trailing whitespace of string s
def trail(s):
    return len(s.rstrip())

for s in ("i am here. ", "nospace", "   no  trail", "All sorts of spaces \t \n", ""):
    i = trail(s)
    print `s`, i, `s[:i]`

出力

'i am here. ' 10 'i am here.'
'nospace' 7 'nospace'
'   no  trail' 12 '   no  trail'
'All sorts of spaces \t \n' 19 'All sorts of spaces'
'' 0 ''
于 2014-10-26T06:54:30.397 に答える
0

@Alexeyが言ったように、正規表現が進む方法のようです。

以下はあなたが望むことをするはずです。「空白」には改行文字が含まれることに注意してください。

次のように呼び出します。list_of_indexes = find_ws("/path/to/file.txt")

import re

def find_ws(filename):
    """Return a list of indexes, each indicating the location of the 
    first trailing whitespace character on a line.  Return an index of 
    -1 if there is no trailing whitespace character (at the end of a file)"""

    text = open(filename).readlines()

    # Any characters, then whitespace, then end of line
    # Use a non-"greedy" match
    # Make the whitespace before the end of the line a group
    match_space = re.compile(r'^.*?\S*?(\s+?)\Z') 

    indexes = []

    for s in text:
        m = match_space.match(s)
        if m == None:
            indexes.append(-1)
        else:
            # find the start of the matching group
            indexes.append(m.start(1)) 

    return indexes

Python の正規表現に関するドキュメントが利用可能です。

于 2014-10-26T06:27:09.583 に答える