1

文字列をループして、エンコーディングに違いがある場合はいつでもスペースを挿入するにはどうすればよいですか? たとえば、次のように入力します。

Bar bar black sheep就是其中 famous 的一家club

この出力が得られるはずです:

Bar bar black sheep 就是其中 famous 的一家 club

次のことを試しましたが、次のより簡単な方法はありますか?

# -*- coding: utf8 -*-
sentence = 'Bar bar black sheep就是其中 famous 的一家club'

currIsAscii = None
prevIsAscii = None
newsentence = ""

for i in sentence:
  try:
    i.decode('ascii')
    currIsAscii = True
  except:
    currIsAscii = False
  if prevIsAscii != currIsAscii:
    newsentence+=" "
    newsentence+=i
  else:
    newsentence+=i
  prevIsAscii = currIsAscii

  while "  " in newsentence:
    newsentence = newsentence.replace("  ", " ")

print newsentence.strip()
4

1 に答える 1

2

これは、Ned Batchelder による、このエンコーディングの良さに関するかなりまともな pycon トークです。私にとって有益であり、あなたにも役立つと思います。

于 2012-12-26T17:22:15.093 に答える