2

標準入力から一連の行を読み取り、解析して評価するR「プラグイン」があります。

...
code <- readLines(f, warn=F)   ## that's where the lines come from...
result <- eval(parse(text=code))
...

現在、コード行を提供するシステムが、コードのあちこちにUTF-8 改行なしのスペース ( U+00A0= ) を親切に挿入することがあります。\xc2\xa0そのparse()ようなキャラクターのチョーク。例:

s <- "1 +\xc2\xa03"
s
[1] "1 + 3"   ## looks fine doesn't it? In fact, the Unicode "NON-BREAK SPACE" is there

eval(parse(text=s))
Error in parse(text = s) : <text>:1:4: unexpected input
1: 1 +?
      ^

eval(parse(text=gsub("\xc2\xa0"," ",s)))
[1] 4

その文字を通常のスペースに置き換えたいのですが、上記のようにこれを行うことができます(ただし、自分の責任で、私は推測します):

code <- gsub('\xc2\xa0',' ',code)

ただし、バイト シーケンス'\xc2\a0'は、2 番目のバイトが0xc2.

おそらくもう少し良く、次のように言えます。

code <- gsub(intToUtf8(0x00a0L),' ',code)

しかし、これは UTF-8 文字列に一般化されません。

UTF-8 文字を含む文字列を入力するための、より適切で表現力豊かな方法はありますか? 一般に、UTF-8 文字列 (ここでは のパターン引数) を表現する正しい方法は何sub()ですか?


編集:明確にするために、16進値を指定して文字列にUTF-8文字を入力することに興味があります。次の例を考えてみましょう ("é"は UnicodeU+00E9であり、UTF-8 で として表現できることに注意してください0xc3a9)。

s <- "Cet été."
gsub("té","__",s)
# --> "Cet é__."
# works, but I like to keep my code itself free of UTF-8 literals,
# plus, for the initial question, I really don't want to enter an actual
# UTF-8 "NON BREAKABLE SPACE" in my code as it would be undistinguishable
# from a regular space.

gsub("t\xc3\xa9","__",s)  ## works, but I question how standard and portable
# --> "Cet é__."

gsub("t\\xc3\\xa9","__",s)  ## doesn't work
# --> "Cet été."

gsub("t\x{c3a9}","__",s)  ## would work in Perl, doesn't seem to work in R
# Error: '\x' used without hex digits in character string starting "s\x"
4

1 に答える 1

2

(以前のものは削除しました。)

EDIT2:

> s <- '\U00A0'
> s
[1] " "
> code <- gsub(s, '__','\xc2\xa0' )
> code
[1] "__"
于 2013-02-06T02:39:34.917 に答える