[Python] Scraping the correct postcodes data in python

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have only been using python for a few months and I am trying to blend my hobby (skating all the london postcodes) with learning to code.

    I found the following data https://github.com/radiac/UK-Postcodes/blob/master/postcodes.csv

    and was able to write the following code which picks a random london postcode

    import csv
    import random


    ran = (random.randint(0,3))
    ran_pc = str(random.randint(1,10))
    post_code_signs = ('N','S','E','W',)



    # Open the CSV file
    with open('postcodes.csv', newline='', encoding='utf-8') as file:
    reader = csv.reader(file)

    # Loop through each row in the CSV file
    for row in reader:
    londonpostcode = row[0]
    for ldn in londonpostcode:
    if londonpostcode[0] == post_code_signs [ran] and londonpostcode[1] == ran_pc:
    lnfive = londonpostcode+ (" ") + row [5]
    print (lnfive)


    This does give me random postcodes but I have several problems , it sometimes gives me a sheffield postcode as it starts with an 'S' at the moment I dont know how to include the other London postcode variations such as 'SE','SW' as this only takes the first slice.

    Holistically I would like this to go onto a website I am building and get people to pick a random London postcode . Once I have figured this out I would like to see if I can get people to select their region and then pick a postcode based on that.

    GO EASY ON THE NEW GUY !!! but thanks in advance for any assistance

    Wanted it to return on London postcodes starting with N,S,E,W and got random sheffield postcodes . The codes also runs into random errors

    Continue reading...

Compartilhe esta Página