[英]Code to get total number of words and number of lines starting with H
我正在学习 python 中的文件处理。 我试图编写一个程序来显示以“H”开头的行数和文件中的总字数。 即使文本文件不是空的,它也只为两者打印了 0。 这里有什么问题?
with open("para.txt","a+") as f:
f.write("As I said: not all things should be left up to god.")
lines = 0
# to display the number of lines starting with H
l = f.readlines()
for i in l:
if i[0] == "H":
lines += 1
print("No. of lines starting with H is", lines)
#to display the total number of words in the file
data = f.read()
split_data = data.split()
count = 0
for i in split_data:
count += 1
print("Total number of words:", count)
print(f.tell())
尝试:
def f(file_path):
with open(file_path) as f:
lines = [line.strip() for line in f.readlines() if line.strip()]
length_of_lines = len(lines)
length_of_lines_start_with_h = len([i for i in lines if i[0] == 'H'])
return [length_of_lines, length_of_lines_start_with_h]
f('b.txt') #supposing a text file in you computer named "b.txt"
# [8, 1] #--> 8 lines, 1 line start with 'H'
with open("para.txt","r") as f:
text=f.readline()
l_text=text.split(".")
lines=0
words=0
word_list=[]
for i in l_text:
splited=i.split(" ")
word_list.append(splited)
if i[0].lower() =="h":
lines+=1
for i in word_list:
if i[0].lower() == "h":
word+=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.