简体   繁体   English

如何在两个 arguments function 中仅打印第一个参数?

[英]how to print only 1st argument in two arguments function?

I have a txt.file and string input as an arguments, given string input my function will print corresponding line/string from the file in a set.我有一个 txt.file 和字符串输入作为 arguments,给定字符串输入我的 function 将从一组文件中打印相应的行/字符串。 And file has one word per line.文件每行一个单词。

def angram(s1,s2):
    st = set()
    if sorted(s1) == sorted(s2):
       st.add(s1)
  return st
angram('my.txt', 'top')

expected output: {'pot'}
but output I get {'pot','top'}

I do not want the string input in set.我不希望在集合中输入字符串。 I want only output result from file.我只想要文件中的 output 结果。 Any way to do that??有什么办法吗??

You need to use Python builtin functions for reading files.您需要使用 Python 内置函数来读取文件。 https://www.geeksforgeeks.org/read-a-file-line-by-line-in-python/ https://www.geeksforgeeks.org/read-a-file-line-by-line-in-python/

Given:鉴于:

car
pto
pot

Output: Output:

{'pot', 'pto'}

Code:代码:

def anagram(s1,s2):
    st = set()
    fh = open('my.txt')
    target = sorted(s2)
    while True:
        line = fh.readline()      # while there is line to read in the file
        check = line.strip('\n')  # some lines will include "\n" in index 0 - remove it
        if sorted(check) == target:
          st.add(check)
        if not line:
            break
    fh.close()
    st.remove(s2) # the user doesn't want the same word as the target (s2) to be included
    return st
anagram('my.txt', 'top')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 仅替换替换第一个参数 - Replace only replacing the 1st argument 如何在 python 类中创建具有一个参数的第一个方法和具有两个参数的第二个方法 - How to create a 1st Method with one Arguments and 2nd Method with two arguments in a python class 当我尝试将numpy数组作为第一个参数传递时,poly函数是否仅将列表作为其第一个参数接受,它显示错误 - Does poly function accept only the list as its 1st argument when I tried to pass an numpy array as an 1st argument it is showing an error 如何在 HTML 标签中打印第一个元素 - how to print 1st element in HTML tag 捕获两个单词之间的字符串,但只有第一次 - Capture string between two words but only 1st time 计算两个日期之间第一天有多少个星期一 - Calculate how many Monday the 1st between two dates 如何获得 numpy 第一个 True Only - how to get numpy where for 1st True Only 如何跳过初始化函数的第一个返回值? -Python - How to skip initializing the 1st returned value from a function? - Python sorted() function in python 在读取文件时仅按第一位数字对数字进行排序。 我正在尝试在 python 游戏中打印高分列表 - sorted() function in python when reading a file sorts numbers by 1st digit only. I'm trying to print a high scores list in a python game for循环只使用dict中的第一个键 - for loop only using 1st key in dict
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM