如何在csv中选择随机单元格

2024-05-12 20:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV文件,这是随机字只。没有标题

例如:

"dawn","go","test","these","swung"
"joy","frequently","seven","congress"

“我的代码”未选择随机单元格并返回错误:

TypeError: '_csv.reader' object is not subscriptable

我的代码是:

    def random_select(self):

        csv_reader = csv.reader("randomwords.csv")       
        words = list(csv_reader)
        random_names = random.choice(words)
        readcsv = csv_reader[random_names][random_names]

        print(''.join(readcsv))

Tags: 文件csv代码testgo标题namesrandom
3条回答

下面是一个修复了即时错误的重构

# There is no class here and no self here   don't use self as argument
def random_select():
    # Open a file handle, pass it to the CSV reader instance
    with open("randomwords.csv") as r:
        # Read all words from all lines into a single list
        words = [word for line in csv.reader(r) for word in line]
    # Pick out two random words
    return ''.join([random.choice(words), random.choice(words)])

内部函数通常应该只是return一个结果;然后,调用方可以print根据自己的意愿返回结果

对于较短的输入列表,同一个单词随机抽取两次的概率非常高。你的问题甚至不清楚你是否真的想要列表中的两个随机单词,但这是我关于代码应该产生什么的最好猜测。如果你想要其他的东西,希望它现在应该是显而易见的改变

每次调用此函数时,再次将CSV文件读入内存的效率极低;可能重构代码,将列表读入内存一次,然后在需要更多单词时从列表中随机挑选出单词

CSV文件可能根本不适合这种用例。自20世纪60年代末以来,存储单词列表的标准方法至少是一个简单的文本文件,每行一个单词或短语

random_names是从words中选取的单个字符串。所以words是可下标的,但除此之外没有其他内容

如果您只是希望将“random\u item random\u item”生成为字符串

    def random_select(self):

        csv_reader = csv.reader("randomwords.csv")       
        lines = list(csv_reader)
        words = lines[0]

        print(''.join(random.choices(words, k=2)))

有效的代码:

def Generate(self):
        rcolumn = random.randint(0, 10)
        rrow = random.randint(0, 66)
        with open('randomwords.csv', 'r') as f:
            mycsv = csv.reader(f)
            mycsv = list(mycsv)
            print(mycsv[rrow][rcolumn])

相关问题 更多 >