回答編集履歴
1
コード分離
answer
CHANGED
@@ -1,34 +1,37 @@
|
|
1
1
|
正規表現でうまく表現できなかったので、状態遷移でコーディングしてみました。
|
2
2
|
空白 or 文字が出現したタイミングで状態を切り替えて処理しています。
|
3
3
|
```Python
|
4
|
+
# 空白はそのまま、文字は{}で囲んで出力
|
5
|
+
|
4
6
|
# 'word' -> '{word}'
|
5
7
|
def quote( word):
|
6
8
|
if len(word):
|
7
9
|
word = '{' + word + '}'
|
8
10
|
return word
|
9
11
|
|
10
|
-
|
12
|
+
# 'a b' -> '{a} {b}'
|
11
|
-
|
13
|
+
def quoteWords(line):
|
12
|
-
if not line.startswith('\t'):
|
13
|
-
continue
|
14
|
-
line = line[1:] # 先頭\t除去
|
15
|
-
|
16
14
|
isSpace = True
|
17
15
|
word, line_new = '',''
|
18
16
|
for s in line:
|
19
17
|
if s == ' ':
|
20
|
-
if not isSpace:
|
18
|
+
if not isSpace:
|
21
19
|
line_new += quote(word)
|
22
20
|
word = ''
|
23
|
-
|
24
21
|
line_new += s
|
25
22
|
isSpace = True
|
26
23
|
else:
|
27
24
|
word += s
|
28
25
|
isSpace = False
|
26
|
+
line_new += quote(word) # 空白以外で終わった場合(積み残し)
|
27
|
+
return line_new
|
29
28
|
|
29
|
+
lines = ['','a\t','\t','\ta','\ ','\ta ','\t a','\ta b','\t aaa bbb cccc dd eeeeee']
|
30
|
-
|
30
|
+
for line in lines:
|
31
|
+
if not line.startswith('\t'):
|
32
|
+
continue
|
33
|
+
line = line[1:] # 先頭\t除去
|
31
|
-
line_new
|
34
|
+
line_new = quoteWords(line)
|
32
35
|
|
33
36
|
print('line[%s]'%line)
|
34
37
|
print('line_new[%s]'%line_new)
|