这是我的数据:
1 2693 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0
1 2694 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0
1 2695 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0
1 2696 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0
1 2697 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0
.
.
.
1 2697 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0
我想将其转换为:
更新后的文件应该格式低于
我想为每一行添加一个字符串值
1 2693 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0 Attack
1 2694 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0 Attack
1 2695 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0 Attack
1 2696 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0 Attack
1 2697 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0 Attack
.
.
.
1 2697 1 80 1 1 1 0 0 1 1 0 1 1 40 0 0 Attack
我想在Scala中编写一个程序来执行上述任务。
程序应该计入数据总线数,然后运行循环次数。
在每次迭代时,程序应为每一行分配一个特定的字符串值。
最后,程序应将新更新的数据写入新文件。
这是一个解决了我的问题的Python代码,但我想要在Apache spark(Scala)中执行相同操作的代码。
import csv
output = open('processed.csv', 'w')
with open("hping3Spoofed.csv") as csvFile:
csvLines = csv.reader(csvFile)
id=0
documents = []
for line in csvLines:
if(id == 0):
line.append("label \n")
id = 1
else:
line.append("Spoof Attack \n")
output.write(', '.join(line))
答案 0 :(得分:2)
正如@Rob和@kali所建议的那样:
import sys.process._
"perl -i -pe 's/$/,Attack/' spootedAttack.csv" #> new java.io.File("out.csv") !
// or
"sed -e 's/$/ Attack/' -i spootedAttack.csv" #> new java.io.File("out.csv") !
如果你想根据行内容添加一些逻辑,你可以访问~160MB的RAM:
import java.nio.file.{Paths, Files}
import java.nio.charset.StandardCharsets
import scala.io.Source.fromFile
import scala.io.Source.fromInputStream
// from the "src/main/resources" dir
// val ob = fromInputStream(getClass.getResourceAsStream("/spootedAttack.csv"))
val ob = fromFile("spootedAttack.csv", "UTF-8")
.getLines
.map(_ + " Attack") // write your logic here
// e.g. .map(line => if(line...) ...)
.mkString("\n")
.getBytes(StandardCharsets.UTF_8)
Files.write(Paths.get("output.csv"), ob)
答案 1 :(得分:1)
这是解决我问题的Python代码
import csv
output = open('processed.csv', 'w')
with open("hping3Spoofed.csv") as csvFile:
csvLines = csv.reader(csvFile)
id=0
documents = []
for line in csvLines:
if(id == 0):
line.append("label \n")
id = 1
else:
line.append("Spoof Attack \n")
output.write(', '.join(line))