是否获取长度最长的单词并删除\n每个字符串后面的


f = open('wordlist.txt','w')
for x in range(4):
u = input('please enter how many words you like to write')
f.write(u + 'n') 
print('it have been wrote into file')

e = 0
y = 0               #y for total length
f = open('wordlist.txt','r')
for x in f:
print(len(x))
y += len(x)
e += 1
if len(x) >= len(x):
z = len(x)       #get largest length

avglength = y/e          #get average length for each line
print(z)            
print(y)
print(avglength)

正如上面的代码,我想得到文件中最大的长度,但它只得到最后一个单词的长度,为什么会发生这种情况?以及如何删除每个字符串后面的'\n',我需要找到每个单词的长度,但长度不正确。例如,"ss"的长度应该为3,在我的代码中,我添加了每行"\n",这可能会导致"ss"长度为4。有什么帮助吗?

您在代码中写入:

if len(x) >= len(x):
z = len(x)  

其将始终是CCD_ 1。因此,您的z将取上一个x的长度值,这将是您的最后一个单词。

您可以通过在for循环之外定义一个max_length变量来跟踪当前的最大长度:

max_length = 0

和在环使用:

max_length = max([len(x), max_length])
if len(x) >= max_length:
z = len(x)
max_length = z

或者,正如你在下面的评论中指出的那样,你可以简单地将整个声明写成:

z = max([len(x), z])

前提是您已将z = 0设置在for循环之外。

这里有一个稍微修改过的计算方法。它可能更容易阅读,并且它使用上下文管理器with来处理打开和关闭文件:

# get words and write to file
with open('wordlist.txt','w') as f:
for x in range(4):
u = input('please enter a word: ')
f.write(u + 'n')
print('Your words have been written into the file')

# read words and count find length of longest word
with open('wordlist.txt') as f:
words = f.readlines()
word_lengths = [len(i.strip()) for i in words]    # get the length of each word in list after removing white space
max_length = max(word_lengths)            # find the longest length
total_length = sum(word_lengths)          # find the total length of all words
average_word_length = total_length / len(words)   # find the average length

您可以使用.split()方法从字符串中删除n

以下是你必须做的:

x = x.split('n')
x = x[0]

您可以将其添加到True0循环中。

这是完整的代码:

f = open('wordlist.txt', 'w')
for x in range(4):
u = input('Please enter the word: ')
f.write(u + 'n')
print('it has been written into file')
z = 0
e = 0
y = 0  # y for total length
f = open('wordlist.txt', 'r')
for x in f:
x = x.split('n')    #Now, x = ['Your Input', '']
x = x[0]             #Select first string
print(len(x))
y += len(x)
e += 1
if len(x) >= z:
z = len(x)  # get largest length
avglength = y / e  # get average length for each line
print(z)
print(y)
print(avglength)

这是运行:

Please enter the word: This
Please enter the word: is
Please enter the word: just
Please enter the word: testing

各自的输出:

4
2
4
7
7
17
4.25

另一种可能的解决方案:

# Use open() as a context manager so you don't have to worry about closing the file.
with open('wordlist.txt','r') as opened:
# Create a list of words in the file.
# words = list(opened)
# EDIT: The traditional way to split some lines and strip
# the newline character.
words = opened.read().strip().split("n")
# Start max_length at negative 1.
max_length = -1
# List object to hold all word lengths.
all_lengths = []
# Number of words written to file
num_of_words = len(words)
# Iterate the list of words.
for word in words:
# Get length of the current word.
current_length = len(word)
# Append the length of the current word to the list.
all_lengths.append(current_length)
# Using all_lengths[-1] gets the latest item on the list
# Also, we only care if the current value is larger than the max value.
if all_lengths[-1] > max_length:
max_length = all_lengths[-1]
# Average length of word per line.
average_length = sum(all_lengths) / num_of_words

最新更新