0

I am a very novice coder who needs help combining and rearranging a lot of .txt data. The file is currently listed as follows:

A

lcorn, MS
Aleutians East, AK
Aleutians West, AK
Alexander, IL
Alexander, NC
Alexandria, VA
Alfalfa, OK
Alger, MI
Allamakee, IA
Allegan, MI
Allegany, MD
Allegany, NY
Alleghany, NC
Alleghany, VA
Allegheny, PA
Allen, IN
Allen, KS
Allen, KY
Allen, LA
Allen, OH
Allendale, SC
Alpena, MI
Alpine, CA
Amador, CA
Amelia, VA
Amherst, VA
Amite, MS

I need to rearrange the data so it reads like

MS: Alcorn
AK: Aleutians East
AK: Aleutians West

Essentially in the format of (State): County. I then need to output the newly completed results into a new text file, there are hundreds of lines in the file and I am unaware of where to even start.

0

3 Answers 3

1

First, you need to iterate over your data reading it one line at a time, then reformat the county, state as state: county.

Try:

with open('data.txt', "r") as fin, open('out.dat', "w") as fout:
    line = fin.readline()    
    while line:
        pos = line.rfind(',')
        if pos > 1:
            # input: Aleutians West, AK
            # reformat AK: Aleutians West
            line = "{}: {}".format(line[pos+1:].strip(), line[0:pos])
            fout.write(line)
        elif line.strip() != '':
            # otherwise no comma so not in county, state form
            print("skip:", line)
        line = fin.readline()

Output:

MS: Alcorn
AK: Aleutians East
AK: Aleutians West
IL: Alexander
NC: Alexander
...

A comma (,) might be found in a county name, so code above is using line.rfind(',') to find the last ',' in the line. If no lines have more than one comma in them then you can safely use line.find(',') to find the first comma.

Next, if you want to sort the output file by state and county then you can do it in Python code or use the "sort" command found on most operating systems.

Sign up to request clarification or add additional context in comments.

Comments

0

If your data is as simple as it looks, a simple answer could be:

with open('outfile.txt','wt') as ofile:
    for line in open('infile.txt','rt'):
        city,state = list(map(lambda x:x.strip(),line.split(","))
        print(f"{state} : {city}",file=ofile)

or something quite similar (not tested.)

Comments

0

string="""lcorn, MS Aleutians East, AK Aleutians West, AK Alexander, IL Alexander, NC Alexandria, VA Alfalfa, OK Alger, MI Allamakee, IA Allegan, MI Allegany, MD Allegany, NY Alleghany, NC Alleghany, VA Allegheny, PA Allen, IN Allen, KS Allen, KY Allen, LA Allen, OH Allendale, SC Alpena, MI Alpine, CA Amador, CA Amelia, VA Amherst, VA Amite, MS"""

 myTuples=[tuple(item.split(',')) for item in string.split("\n")]
 myDict={}
 for (key,value) in myTuples:
     myDict[key]=value

 result={k: v for k, v in sorted(myDict.items(), key=lambda item: item[1])}
 print(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.