質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Q&A

解決済

1回答

1731閲覧

Ruby, (.txt)ファイルの読み込み,文字化け

wpx-vv1uZ

総合スコア23

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

0グッド

0クリップ

投稿2019/06/26 02:10

編集2019/06/26 02:34

前提・実現したいこと

rubyで(.txt)ファイルを読み込んで、改行区切りの配列に変換したいです。

発生している問題・エラーメッセージ

実行はできるのですが、文字コードが違うのか文字化けしてしまいます。 配列になっているかも確認できません。

該当のソースコード

ruby

1cording: utf-8 2 3words_sorted = [] 4begin 5 IO.foreach('./words_sorted.txt') do |keys| 6 words_sorted.push(keys) 7 end 8end 9 puts words_sorted 10

###実行結果

P!ߤ?lZ[Content_Types].xml ?(????n?0E?????Ub袪*?>?-R?{V??Ǽ??QU? l"%3??3Vƃ?ښl ?w%?=???^i7+???-d&?0?A?6?l4??L60#?Ò?S O????X??*??V$z?3??3??????%p)O?? ~~~~ `!word/settings.xmlPK!Mz?????%docProps/core.xmlPK!n?K-X??(word/fontTable.xmlPK!?ԍ?'?:+word/webSettings.xmlPK!<?TT q?,word/styles.xmlPK!??Ni|?8docProps/app.xmlPK ??:

(words_sorted.txt)ファイルの中身

a about across actually advice advise afraid after afterwards again against air alas alice all almost along aloud altogether am among an and another answer antipathies anxiously any anything apple are as ask asking at ate australia away back bank bat bats be beasts beautifully because beds been before began begin beginning begun behind belong best bit bleeds blown book bottle box brave bright brightened bring burn burning burnt but buttered by cake came can candle care cat catch cats centre certain certainly chain cheated cherry child children climb close come coming common considering conversations cool corner could couldn country creep cried croquet crying cupboards curiosity curious currants curtain curtsey curtseying custard cut daisies daisy dark day dear decided deep deeply delight did didn dinah dipped disagree disappointment distance do don door doors doorway down downwards dozing dream dreamy drink drop dry dull earnestly ears earth eat eaten eats either else empty end enough even ever every except expecting eye eyes face fact fall fallen falling fancy fear feel feeling feet fell felt few field fifteen filled find finding finger finished first fitted flame flashed flavour flowers followed fond for forgotten found fountains four friends from funny further game garden gave generally get getting girl glad glass go going golden good got grand great grow growing had half hall hand hanging happen happened happens hardly have having head heads heap hear hedge her here herself high hold holding hole home hope hoping hot house how however hung hurried hurry hurrying hurt i idea if ignorant impossible in inches indeed into is it its itself jar jumped just key killing knelt knife know knowledge label labelled lamps large larger late lately later latitude learnt leave leaves led left legged legs lessons let letters life like likely listen listening lit little ll lock locked locks long longed longer longitude look looked looks lost loveliest lovely low lying m ma made make makes making manage managed many maps marked marmalade matter me mice middle might miles milk mind minute minutes miss mixed moment more mouse much must my name natural near neck nervous never new next nice night no nor not nothing noticed now occurred of off oh on once one only open opened opportunity or orange other ought out over overhead own paper passage passed past peeped pegs people perhaps person picking pictures pine pink plainly playing please pleasure plenty pocket poison poker poor pop possibly practice presently pretend pretending printed put question quite rabbit ran rat rate rather re reach read reading really red remained remarkable remember remembered respectable right roast roof room round row rules s sadly said same sat saucer saw say saying school scolded second see seem seemed seen seldom set several severely shall sharply she shelves should shoulders showing shrink shut shutting side sides sight simple sister sitting size sleepy slippery slowly small smaller so solid some somebody sometimes somewhere soon sooner sort sound spoke stairs started sticks still stopping stories straight stupid such suddenly sure surprised t table take talking tart taste taught tea tears telescope telescopes tell ten than that the their them then there they thing things think this those though thought thousand three through thump tied time tiny tired to toast toffy too took top tried trouble true truth trying tumbling tunnel turkey turned twice two under underneath unpleasant up upon use usually ve ventured very waistcoat waited waiting walk walked walking wander was watch way well went were what when whether which while whiskers white who why wild will wind wise wish with without wonder wondered wondering word words work world worth would wouldn written yes you your zealand

補足情報(FW/ツールのバージョンなど)

Macbook proを使っています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

mather

2019/06/26 02:29

テキストファイルの中身もコードブロックで囲みましょう。 コピペが簡単になりますし、自動的に短く表示してくれます。
wpx-vv1uZ

2019/06/26 02:35

ご指摘ありがとうございます。 コードブロックがなにか分からなかったのですが、これで大丈夫でしょうか?
mather

2019/06/26 02:37

はい。大丈夫です。
guest

回答1

0

ベストアンサー

テキストファイルとしているものが単純なテキストファイルではない可能性があります。

$ file words_sorted.txt

でファイルフォーマットを確認してください。
正常なテキストファイルなら

words_sorted.txt: ASCII text

と表示されるはずです。

投稿2019/06/26 02:37

mather

総合スコア6753

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

wpx-vv1uZ

2019/06/26 02:39

ターミナルの実行結果をwordに貼ってそれの拡張子を.txtに変えたので (words_sorted.txt: Microsoft Word 2007+) と表示されました。。。
mather

2019/06/26 05:41

つまりテキストファイルではないですね…。拡張子を変えるのではなく、テキストファイルとして保存してください。 Rubyのソースコードを書いたエディタがあると思いますので、そちらでファイルを作成してください。
mather

2019/06/26 05:47 編集

なお、Wordでも「名前をつけて保存」から「プレーンテキスト(.txt)」が保存形式として選べます。
wpx-vv1uZ

2019/06/26 06:35

回答ありがとうございます。 atomに貼ると正常に動きました。 お付き合い頂きありがとうございました m__m
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問