小编pup*_*kik的帖子

如何用星号替换切成薄片的单词的剩余部分?

因此,我正在尝试制作一个简单的小脚本,该脚本需要一个字符串,将其切成指定字符,然后用星号(*)替换单词的其余部分。下面的例子。

def multi_blank(strng, ch_count):
    """
    >>> multi_blank("banana", 1)
    'b*****'
    """
Run Code Online (Sandbox Code Playgroud)

当我尝试学习切片和索引编制时,总是会遇到麻烦。我设法切成指定的数字,但无法弄清楚如何用星号代替单词的其余部分。

    return strng[:ch_count] + "*" + strng[ch_count:]
Run Code Online (Sandbox Code Playgroud)

以上是我尝试过的内容,但返回以下内容:

Expected:
    'b*****'
Got:
    'b*anana'
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

    string = strng.replace(strng[ch_count:], '*')
    return string
Run Code Online (Sandbox Code Playgroud)

简短的解释将对您的帮助有所帮助。赞赏!

python

3
推荐指数
1
解决办法
69
查看次数

在调用不同文件的函数中,以某个字符结尾的单词有多少个?

因此,我正在尝试制作一个小的函数,该函数以文件名作为参数并返回文件中以“!”,“?”结尾的单词数。要么 ”。”。

到目前为止,我已经尝试了以下方法:

def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count
Run Code Online (Sandbox Code Playgroud)

但这不起作用,也不计算在单独的调用文件中有多少个以这些指定字符结尾的单词。我曾想过拆分每个单词并循环遍历每个字符,如果它包含一个字符,它将为计数增加+1,但是我不确定该怎么做。

编辑:还想到只使用.count吗?那行得通吗?干杯

edit2:这是我要通过的doctest:

def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """
Run Code Online (Sandbox Code Playgroud)

这是失败的.txt的链接:https : //pastebin.com/raw/1NYPeY29

这是说期望值:45分:52

python

3
推荐指数
1
解决办法
80
查看次数

用_(下划线)替换.txt文件\ n(换行)的函数?

我正在尝试编写一个函数,该函数以文件名作为参数并返回一个字符串,其中所有\n字符均替换为该_字符。

这是我所做的:

def replace_space(filename):
    wordfile = open(filename)
    text_str = wordfile.read()
    wordfile.close()
    text_str.replace("\n", "_")

replace_space("words.txt")
Run Code Online (Sandbox Code Playgroud)

我还尝试使用“”代替“ \ n”:

    text_str.replace(" ", "_")
Run Code Online (Sandbox Code Playgroud)

python

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

标签 统计

python ×3