pythonでスクレイピングプログラムを書いている際に.txt
ファイルから文字を読み込みたい際につまずいた点があったので残します
sample.txt
soccer
baseball
word
excel
point
address
japan
amazon
mac
apple
iphone
starbucks
このような.txt
ファイルがあったとします
sample.py
with open('word.txt', encoding='shift_jis') as keywords:
for keyword in keywords:
print(keyword)
このような形でキーワードの読み込みを行い出力をした際に当然上記のファイルのような出力結果を期待していたのですが
soccer
baseball
word
excel
point
address
japan
amazon
mac
apple
iphone
starbucks
このような形で出力されていました。中に改行文字が含まれていたのですね。
pythonの.strip()
というメソッドが空白文字(ここでは改行)を打ち消してくれるのでこのようにしました
sample.py
with open('word.txt', encoding='shift_jis') as keywords:
for word in keywords:
keyword = word.strip()
print(keyword)
そうすると出力結果は最初に読みこんだ.txt
ファイルと同じような期待していた出力結果になりました。
python初めて触ったのですが便利なメソッドが多くていいなと個人的に思ったのでこれから趣味レベルで触っていこうと思います