开发者

Import strings from .txt and searching for first numeric character - python

I am a total noob with python (programming in fact) but I hope you can help :)

I have a .txt file wi开发者_如何学Cth a list of strings containing addresses.

I want to import it to Python and then search for the first numberic character and then create a new column for it...like

input

'Elm Street 12' 
'Baker Street 143'

and output

'Elm Street 12' , 12
'Baker Street 143' , 14

and save it to .txt.

I am trying to do if from the windows cmd.

Thank you in advance.


You probably want to use a dict. Loop through and use re to find your numeric characters, use that as a key in the dict to each string. If you expect to have duplicates.

import re
results = {}
for s in ['Elm Street 12', 'Baker Street 143']:
    match = re.search(r'\d+', s)
    if match:
        results[match.group()] = s

>>> results
<<< {'12': 'Elm Street 12', '143': 'Baker Street 143'}


with open('file.txt') as inn:
    for line in inn:
        print "%s %s" % (line, [int(item) for item in line.split(' ') if item.isdigit()])


This might be what you are looking for

import re

input = '''Elm Street 12
Baker Street 143'''
output = ""

rows = input.split("\n")
for row in rows:
    m = re.search(r'\d+', row)
    output += "{0} {1}\n".format(row, m.group())

print output


import re
regx = re.compile("^('.+ (\d+)')",re.MULTILINE)

with open('Copie de fileinput.txt','r+') as f:
    mod = regx.sub('\\1 , \\2',f.read())
    f.seek(0,0)
    f.write(mod)

Note that I understood that there are quotes ' in the file. I doubt of that, but your output have quotes in it, so my regex has quotes.... You will remove thgem if there are no quotes in fact

Intead of recording data in a flat file, you should better use the pickle module

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜