Yethrosh Yethrosh - 1 month ago 8
Python Question

Auto Increment in wikitable using python

I have mediawiki user statistics in wikitable format, which have been generated by sql query.
Now I would like to replace all

#
exist in first column and in every row to auto increment numbers i.e 1,2,3,4 starting from first row using python script.

Any idea how to accomplish this task?

Data in wikitable format:

matter = """{| class="wikitable"
!number!!user_id!!user_name!!byte_count!!edit_count
|-
|#||19745||[[user:abc|abc]]||37294210.0||83282
|-
|#||21818||[[user:abc|abc]]||3420248.0||121794
|-
|#||21548||[[user:abc|abc]]||2515274.0||32799
|}"""

with open("wikit.txt", 'w') as f:
f.write(matter)

with open('wikit.txt', 'r') as f:
m = f.read()

print(m)

Answer

Haven't tested but it should work for you

   with open('wikit.txt', 'r') as f:
        lines = f.readlines()
    newlines =[]
    line_num=1
    for line in lines:
        newlines.append(line.replace("#",str(line_num)))
        if "#" in line:
           line_num+=1

   newlines_str='\n'.join(line for line in newlines)

    with open("wikit.txt", 'w') as f:
        f.write(newlines_str)
Comments