我正在嘗試獲取一行中的第一個單詞(例如蘋果、書、椅子)。我有一長串法語單詞及其在英語中的含義:
French,English
partie,part
histoire,history
chercher,search
seulement,only
police,police
...
此串列存盤在 csv 中。我想從這個串列中得到一個隨機的法語單詞。有人知道我該怎么做嗎?
我的代碼(當前):
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)
uj5u.com熱心網友回復:
您可以使用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
uj5u.com熱心網友回復:
如果串列很大,則將 csv 加載到資料框中
import pandas as pd
df = pd.read_csv('french_words.csv')
df['French'].sample()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/491997.html
