Python:行中的字数

Python:行中的字数,python,Python,我有一个有很多行的文件。我只需要数一数第35行的字数。有没有简单的方法可以做到这一点?给你 num_words = None num_lines = 0 with open(filename, 'r') as f: for line in f: num_lines += 1 if num_lines == 35: num_words = len(line.split()) break print('The

我有一个有很多行的文件。我只需要数一数第35行的字数。有没有简单的方法可以做到这一点?

给你

num_words = None
num_lines = 0
with open(filename, 'r') as f:
    for line in f:
        num_lines += 1
        if num_lines == 35:
            num_words = len(line.split())
            break

print('The number of words on line 35 is ' + str(num_words))
无循环:

with open(file, 'r') as f:
    print(len(f.split('\n')[34].split()))

到目前为止你都试了些什么?是的。此外,您可能需要检查此项