I have a text file that needs to be sorted by the first column and merge all repeats with the count to the left of the data, and then write the sorted/counted data into an already created csv file.
Ex text file:
, 00.000.00.000, word, 00
, 00.000.00.001, word, 00
, 00.000.00.002, word, 00
, 00.000.00.000, word, 00
, 00.000.00.002, word, 00
, 00.000.00.000, word, 00
Ex result:
, 3, 00.000.00.000, word, 00
, 1, 00.000.00.001, word, 00
, 2, 00.000.00.002, word, 00
My code:
for ip in open("list.txt"):
with open(ip.strip()+".txt", "a") as ip_file:
for line in open("data.txt"):
new_line = line.split(" ")
if "blocked" in new_line:
if "src="+ip.strip() in new_line:
ip_file.write(", " + new_line[11])
ip_file.write(", " + new_line[12])
ip_file.write(", " + new_line[13])
for ip_file in os.listdir(sub_dir):
with open(os.path.join(sub_dir, ip_file), "a") as f:
data = f.readlines()
data.sort(key = lambda l: float(l.split()[0]), reverse = True)
Whenever I test the code, I get the error TypeError: 'str' object is not callable or something similar. I can't use .split() .read() .strip() etc without getting the error.
Question: How can I sort the files' contents and count repeating lines (without defining a function)?
I'm basically trying to:
sort -k1 | uniq -c | sed 's/^/,/' >> test.csv
解决方案D = {}
for k in open('data.txt'): #use dictionary to count and filter duplicate lines
if k in D:
D[k] += 1 #increase k by one if already seen.
else:
D[k] = 1 #initialize key with one if seen for first time.
for sk in sorted(D): #sort keys
print(',', D[sk], sk.rstrip(), file=open('test.csv', 'a')) #print a comma, followed by number of lines plus line.
#Output
, 3, 00.000.00.000, word, 00
, 1, 00.000.00.001, word, 00
, 2, 00.000.00.002, word, 00