I have to use the values of the "nm" and count the number of "nm" in the entire file so that I could create a count column that would be the number of times that the text "nm" appears in the entire file. Then I need to do the same thing for the other rows and I need to write the results into a new file.
I have been working on this problem for the last 3 days and I am a beginner in the coding world. I would really appreciate if someone could help me with this problem.
Thanks a lot for your time and help.
Regards.
A:
If the rows with "nm" are named "nm1", "nm2" etc, then something like:
import re
with open("file.csv", "r") as f:
reader = csv.reader(f, delimiter=";")
# split each row into a list
for row in reader:
# use regular expressions to find each occurrence of "nm" in the row
# add 1 to the return value of each match
print(1 + sum(m.group(1) for m in re.finditer(r"nm", row)))
The first line of the file contains the text of each row, but you can ignore that if you like. If you use Python 3.x you should use print(1 + sum(m.group(1) for m in re.finditer(r"nm", row))) instead.
Note that there is nothing to stop a row from containing multiple "nm"s, so you would want to find some way of accounting for that. It might be easier to use the "nm" as the line separator, and just do some processing before calling the csv.reader:
import re
with open("file.csv", "r") as f:
# split each line into a list
for line in f:
# remove the last character if any and replace it with a new line
line = line[:-1] + ";
"
# use regular expressions to find each occurrence of "nm" be359ba680
Related links:
Comments