一道综合题,能否用最简单的代码编写出来呢?
Let's mix the function, context manager, basic data structures, loops, conditional executions, statementassignment, and f strings concepts and syntax we have learnt so far to solve this problem.
You may use the sample file (iso.txt) shared on Ed code section to test your code.
Hint:
Read file use open( ) function;
Split lines using split( ) function;
You may also count words use get( ) function to simplify a bit.
The get() method returns the value of the item with the specified key.
Syntax: dictionary.get(keyname, value)
keyname (Required) - The keyname of the item you want to return the value from
value (Optional) - A value to return if the specified key does not exist. Default value None # 打开文件并读取内容
with open('iso.txt', 'r') as f:
lines = f.read().splitlines()
# 定义一个字典来存储单词的出现次数
word_count = {}
# 遍历每一行文本
for line in lines:
# 分割行成单词列表
words = line.split()
# 遍历每个单词
for word in words:
# 将单词添加到字典中并更新其出现次数
word_count = word_count.get(word, 0) + 1
# 输出每个单词出现的次数
for word, count in word_count.items():
print(f"'{word}' 出现了 {count} 次")
鱼币 币 isdkz 发表于 2023-3-16 21:19
币
{:10_256:}{:10_256:}{:10_256:} 根据题目描述,我们需要编写一个程序来读取一个文件并计算该文件中每个单词的出现次数。
我们可以使用以下步骤来实现这个程序:
1、打开文件并读取文件内容。
2、将文件内容拆分为单词列表。
3、创建一个空字典,用于存储每个单词及其出现次数。
4、使用循环和条件执行语句遍历单词列表,并将每个单词添加到字典中,如果单词已经存在,则增加其出现次数。
5、打印每个单词及其出现次数。
下面是一个可以实现这些步骤的代码示例:
def count_words(filename):
# Step 1: Open and read the file
with open(filename, 'r') as file:
content = file.read()
# Step 2: Split the file content into a list of words
words = content.split()
# Step 3: Create an empty dictionary to store word counts
word_counts = {}
# Step 4: Loop over each word and add it to the dictionary, incrementing the count if it already exists
for word in words:
if word in word_counts:
word_counts += 1
else:
word_counts = 1
# Step 5: Print the word counts using f-strings
for word, count in word_counts.items():
print(f'{word}: {count}')
count_words('iso.txt')
在这个示例中,我们定义了一个名为 count_words 的函数,它需要一个文件名作为输入。
然后,我们使用上下文管理器打开文件并读取文件内容。
接着,我们使用 split 函数将文件内容拆分为单词列表。
接下来,我们创建一个空字典来存储每个单词及其出现次数。
然后,我们使用循环遍历单词列表,并将每个单词添加到字典中。如果单词已经存在,则增加其出现次数。
最后,我们使用 f-strings 打印每个单词及其出现次数。
sfqxx 发表于 2023-3-16 21:21
{:10_256:} sfqxx 发表于 2023-3-16 21:17
鱼币
{:10_256:} isdkz 发表于 2023-3-16 21:24
根据题目描述,我们需要编写一个程序来读取一个文件并计算该文件中每个单词的出现次数。
我们可以使用以 ...
大哥的答案也非常好,不过可惜最佳答案只能给一个{:10_254:} liuhongrun2022 发表于 2023-3-16 20:51
能再请问一下怎么把iso.txt文件导入pycharm嘛? isdkz 发表于 2023-3-16 21:24
根据题目描述,我们需要编写一个程序来读取一个文件并计算该文件中每个单词的出现次数。
我们可以使用以 ...
请问大佬,怎么样才可以用pycharm加载本地的这个文件呢?具体操作可以讲一下吗? 纯爱战士Dylan1 发表于 2023-3-17 10:39
能再请问一下怎么把iso.txt文件导入pycharm嘛?
拖拽
页:
[1]