テキストファイルの各行に対してPythonスクリプトを実行する

テキストファイルの各行に対してPythonスクリプトを実行する

次のタスクを bash で実行するにはどうすればよいですか?

テキスト ファイルの各行を個別に入力として Python スクリプトを実行し、その結果を、ファイルを読み取った行にちなんで名付けられた json ファイルに保存するスクリプトを作成する必要があります。

したがって、テキスト ファイル 10tweets.txt は次のようになります。

猫10ツイート.txt

Trump on the other hand goes all in on water boarding AND some. #GOPDebate
RT @wpjenna Donald Trump promises that he will not touch the 2nd amendment -- "unless we're going to make it stronger."
Trump 23%, Rubio 19%, Kasich & Bush 14%, Christie 10%, Cruz 9% #NHPrimary
@realDonaldTrump Thank you for saying you won't use vulger language anymore. Talk about Sanders & Clinton. Take Cruz as VP. Mexican votes!!!
RT @SurfPHX Mr. Trump @realDonaldTrump tweeted 25 minutes ago. You all do realize, that our future President hardly sleeps. He's a Fighter and a Worker!
go, Bernie #DemDebate
Sanders calls out Clinton on taking Foreign Policy advice from Warmonger Henry Kissinger https://t.co/xT5J4uh4m4 via @YouTube
Cruz, Rubio, and the Moral Bankruptcy of Progressive Identity Politics https://t.co/kSQstJXtKO via @NRO
RT @scarylawyerguy "Who does Bernie Sanders listen to on foreign policy." - A question Hillary had to raise b/c the media will not. #DemDebate
Why Did U of California Fire Tenured Riverside Professor? / Ted Cruz and Higher Ed -- ... - https://t.co/zFxa4Q70wh

出力フォルダーに 1.json、2.json、3.json、4.json、5.json のような出力が作成されるようにします。

bashスクリプトでどのように使用してexec entity_sentiment.py "$@"ファイルの各行にリンクするかはわかりません。スクリプトの実行方法は次のとおりです。

$ python entity_sentiment.py sentiment-entities-text "Thank you for saying you won't use vulger language anymore"
Mentions: 
Name: "vulger language"
  Begin Offset : 35
  Content : vulger language
  Magnitude : 0.699999988079071
  Sentiment : -0.699999988079071
  Type : 2
Salience: 1.0
Sentiment: magnitude: 0.699999988079071
score: -0.699999988079071

たとえば、スクリプトへの入力はファイルの最初の行であると想定できます。

基本的に、次のbashスクリプトを実行すると、ファイルの最後の行のみが解析され、1.jsonに保存されます。

#!/bin/bash

n=1

while read -u 3 -r line; do
  python entity_sentiment.py sentiment-entities-text "$line" > "$((n++)).json"
done 3< 10tweets.txt

以下は、bash IRC チャネルで提案を実行したときに何が起こるかを示すスニペットです。https://pastebin.com/raw/VQpPFJYsそしてhttps://pastebin.com/raw/GQefrTX0

答え1

read入力ファイルを1行ずつ読み、次のように各行にコマンドを適用することができます。

#!/bin/bash

n=1

while read -r line; do
  python entity_sentiment.py sentiment-entities-text "$line" > "$((n++)).json"
done < input.txt

exec entity_sentiment.py "$@"どのように役立つのかわかりません。

答え2

IRC bashコミュニティに感謝

#!/bin/bash

n=1

while read -u 3 -r line; do
  echo $n "${line::30}"
  python entity_sentiment.py sentiment-entities-text "$line" > "$((n++)).json"
  ((n++))
done 3< 10tweets.txt

関連情報