我有一个文件,其中包含一个城市名称,然后文件中每行包含一个州名称。我想计算一个状态名称出现的次数并返回值。
例如,如果我的文件包含:
Los Angeles California
San Diego California
San Francisco California
Albany New York
Buffalo New York
Orlando Florida
Run Code Online (Sandbox Code Playgroud)
我想返回每个州名出现的次数。我有这个给加利福尼亚。
for line in f:
California_count=line.find("California")
if California_count!=-1:
total=line.count("California")
print(total)
Run Code Online (Sandbox Code Playgroud)
这只会给我值 1,我假设这是因为它每行出现 1 次。我如何让它返回数字 3 而不是数字 1?
我有python编程的在线练习题.我坚持这个问题:
Write the definition of a class WeatherForecast that provides the following behavior (methods):
A method called set_skies that has one parameter, a String.
A method called set_high that has one parameter, an int.
A method called set_low that has one parameter, an int.
A method called get_skies that has no parameters and that returns the value that was last used as an argument in set_skies .
A method called get_high that has no parameters and that returns the value …Run Code Online (Sandbox Code Playgroud) 我是Python新手。我有一份文档,每行有一个随机单词。这个文件有几千个字。我试图只打印四个字母长的单词。我试过这个:
f=open("filename.txt")
Words=f.readlines()
for line in f:
if len(line)==4:
print(line)
f.close()
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时,python 是空白的。我假设我也需要去掉空格,但是当我这样做时
f.strip()
Run Code Online (Sandbox Code Playgroud)
我收到一条错误,指出 .strip() 不适用于列表项。任何帮助都是感激不尽。谢谢!