【问题标题】:Extracting acronyms from each string in list index从列表索引中的每个字符串中提取首字母缩写词
【发布时间】:2019-09-12 08:06:43
【问题描述】:

我有一个从文件导入的字符串列表(其他帖子只有单个单词或整数),我无法使用嵌套循环将索引中的每个单词分隔到自己的列表中,然后将每个首字母创建首字母缩略词。

我尝试分离每个索引并通过另一个循环处理它以获取每个单词的第一个字母,但我得到的最接近的是从原始层中提取每个索引的每个第一个字母。

text = (infile.read()).splitlines()
    acronym = []
    separator = "."
    for i in range(len(text)):
        substring = [text[i]]
        for j in range(len(substring)):
            substring2 = [substring[j][:1])]
            acronym.append(substring2)
            print("The Acronym is: ", separator.join(acronym))

Happy Path:多字串列表将被翻译成带有换行符的首字母缩略词。 最后应该输出的示例:D.O.D. \n 美国国家安全局\n 等等。

到目前为止发生了什么:在我得到它在句子级别获取每个索引的第一个单词的第一个字母之前,但我还没有弄清楚如何嵌套这些循环以获取每个索引的单个单词.

有用的知识:分割线后的开头格式(因为人们无法阅读此内容)是一个索引列表,其语法如下:['Department of Defense', 'National Security Agency', ...]

【问题讨论】:

标签: python-3.x


【解决方案1】:

你所拥有的有点乱。如果您要重用代码,通常最好将其变成一个函数。试试这个。

def get_acronym(the_string):
    words = the_string.split(" ")
    return_string = ""
    for word in words:
        return_string += word[0]
    return return_string

text = ['Department of Defense', 'National Security Agency']
for agency in text:
    print("The acronym is: " + get_acronym(agency))

【讨论】:

  • 这是一个更大的程序的一部分,不幸的是它必须从差异中读取。文件。
  • 这不适用于您的初始格式吗? ['Department of Defense', 'National Security Agency', ...]?您只需要在返回字符串的每个 += 后添加一个点。
【解决方案2】:

我想出了如何从文件中做到这一点。文件格式是这样的:

['This is Foo', 'Coming from Bar', 'Bring Your Own Device', 'Department of Defense']

所以如果这也对任何人有帮助,请享受~

infile = open(iname, 'r')
        text = (infile.read()).splitlines()
        print("The Strings To Become Acronyms Are As Followed: \n", text, "\n")
        acronyms = []
        for string in text:
            words = string.split()
            letters = [word[0] for word in words]
            acronyms.append(".".join(letters).upper())

        print("The Acronyms For These Strings Are: \n",acronyms)

此代码输出如下:

要成为缩写的字符串如下:

['This is Foo', 'Coming from Bar', 'Bring Your Own Device', 'Department of Defense']

这些字符串的首字母缩写词是:

['T.I.F', 'C.F.B', 'B.Y.O.D', 'D.O.D']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 2023-04-09
    • 2011-01-20
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多