[英]How can I read a line from a file and split it
我被一些代碼困住了,我無法讓它工作。
from random import randint
def random_song():
global song
linenum = randint(1,43)
open('data.txt')
band_song = readlines."data.txt"(1)
global band
band = band_song.readlines(linenum)
song = band_song.split(" ,")
我想要做的是在文本文件的第一行和最后一行之間生成一個隨機數,然后讀取該特定行。 然后將該行拆分為 2 個字符串。 例如:第 26 行,“鐵娘子,歌劇魅影”分裂為“鐵娘子”,然后是“歌劇魅影”
另外,如何將第二個字符串拆分為每個單詞的第一個字母,並使其適用於每個單詞的任何長度和字母數以及單詞數?
謝謝你,MiniBitComputers
拆分字符串中有一個空格,您不需要它,只需在','
上拆分並使用.strip()
去除結果外部的空格。
閱讀代碼時也有一些奇怪的代碼。 並且您正在拆分讀取行列表,而不僅僅是要讀取的行。
也不需要使用全局變量,這是一種不好的做法,幾乎在所有情況下都最好避免。
所有固定的:
from random import randint
def random_song():
with open('data.txt') as f:
lines = f.readlines()
artist, song = lines[randint(1,43)].split(',')
return artist.strip(), song.strip()
print(random_song())
請注意,一旦with
塊結束,使用with
確保文件關閉。
至於獲取每個單詞的第一個字母:
s = 'This is a bunch of words of varying length.'
first_letters = [word[0] for word in s.split(' ')]
print(first_letters)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.