如何在 bash 中執行以下任務?
我需要編寫一個腳本,在文字檔案的每一行上單獨執行 python 腳本作為輸入,然後將結果保存在以讀取檔案的行命名的 json 檔案中。
因此文字檔 10tweets.txt 如下所示:
貓 10tweets.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
逐行輸入檔案並使用類似的命令將命令應用於每一行
#!/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