Home > Enterprise >  How to get the first word in a line Python
How to get the first word in a line Python

Time:06-17

I am trying to get the first word in a line (e.g. apple, book, chair). I have a long list of French words and their meanings in English:

French,English
partie,part
histoire,history
chercher,search
seulement,only
police,police
...

This list is stored in a csv. I want to get a random French word from this list. Does anybody know how I can do this?

My code(currently):

import random
with open('data/french_words.csv', 'r') as french_words:
    french_words_list = french_words.readlines()
rand_french_word = random.choice(french_words_list)

CodePudding user response:

You can use split:

import random

with open("words.txt") as f:
    next(f) # skip one line (i.e., the header)
    words = [line.split(',')[0] for line in f]

random_word = random.choice(words)
print(random_word) # histoire

CodePudding user response:

Load csv into a dataframe if the list is big

    import pandas as pd
    df = pd.read_csv('french_words.csv')
    df['French'].sample()



  • Related