小编Lef*_*rou的帖子

将.txt文件的前30个字符添加到变量

所以我有这个作业问题:

将的前30个字符school_prompt.txt作为字符串分配给变量beginning_chars

在上一个问题中,我设法对txt文件中的所有字符进行计数,但是我不知道如何将前30个字符添加到变量中。

fname = "school_prompt.txt"
lines = 0
nwords = 0
beginning_chars = 0 
with open(fname, 'r') as f:
    for line in f:
        if line >= 30:
            words = line.split()
            lines +=1 
            nwords += len(words)
            beginning_chars += len(line)
Run Code Online (Sandbox Code Playgroud)

python string variables add character

0
推荐指数
1
解决办法
144
查看次数

如果字符 'p' 在单词中,则将该单词添加到列表变量中

所以我的作业是这样的:使用文件 school_prompt.txt,如果字符 'p' 在一个单词中,则将该单词添加到名为 p_words 的列表中。

我不确定我取得了什么进展,但我被卡住了。

wordsFile = open("school_prompt.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()
p_words = 0

for words in wordList:
    if words[0] == 'p':
        p_words += 1

Run Code Online (Sandbox Code Playgroud)

python

0
推荐指数
1
解决办法
1965
查看次数

标签 统计

python ×2

add ×1

character ×1

string ×1

variables ×1